13 using System.Collections.Generic;
16 namespace System.Threading.Tasks.Schedulers
28 private readonly LinkedList<Task> _tasks =
new LinkedList<Task>();
32 private int _delegatesQueuedOrRunning = 0;
41 if (maxDegreeOfParallelism < 1)
throw new ArgumentOutOfRangeException(
"maxDegreeOfParallelism");
42 _maxDegreeOfParallelism = maxDegreeOfParallelism;
54 if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
56 ++_delegatesQueuedOrRunning;
57 NotifyThreadPoolOfPendingWork();
67 ThreadPool.UnsafeQueueUserWorkItem(_ =>
71 _currentThreadIsProcessingItems =
true;
82 if (_tasks.Count == 0)
84 --_delegatesQueuedOrRunning;
89 item = _tasks.First.Value;
94 base.TryExecuteTask(item);
98 finally { _currentThreadIsProcessingItems =
false; }
109 if (!_currentThreadIsProcessingItems)
return false;
112 if (taskWasPreviouslyQueued) TryDequeue(task);
115 return base.TryExecuteTask(task);
123 lock (_tasks)
return _tasks.Remove(task);
127 public sealed
override int MaximumConcurrencyLevel {
get {
return _maxDegreeOfParallelism; } }
133 bool lockTaken =
false;
136 Monitor.TryEnter(_tasks, ref lockTaken);
137 if (lockTaken)
return _tasks.ToArray();
138 else throw new NotSupportedException();
142 if (lockTaken) Monitor.Exit(_tasks);
static bool _currentThreadIsProcessingItems
Whether the current thread is processing work items.
sealed override bool TryDequeue(Task task)
Attempts to remove a previously scheduled task from the scheduler.
LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the specified degree o...
void NotifyThreadPoolOfPendingWork()
Informs the ThreadPool that there's work to be executed for this scheduler.
sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
Attempts to execute the specified task on the current thread.
sealed override IEnumerable< Task > GetScheduledTasks()
Gets an enumerable of the tasks currently scheduled on this scheduler.
sealed override void QueueTask(Task task)
Queues a task to the scheduler.
readonly int _maxDegreeOfParallelism
The maximum concurrency level allowed by this scheduler.
Provides a task scheduler that ensures a maximum concurrency level while running on top of the Thread...