.Net TPL: Limited Concurrency Level Task scheduler with task priority?

The Parallel Extensions Extras Samples. already provide such a scheduler, the QueuedTaskScheduler. This scheduler provides priorities, concurrency limits, fairness and fine-grained control over the type and priorities of the threads used. Of course, you don’t have to use or configure the features you don’t need.

Stephen Toub provides a brief description of the various schedulers in the Parallel Extensions Extras here

To use the QueuedTaskScheduler, you call its ActivateNewQueue method with the priority you need. This method returns a new TaskScheduler-derived Queue object managed by the parent TaskScheduler. All tasks that use a specific queue are scheduled by the parent TaskScheduler according to their priorities.

The following code creates a scheduler with a maximum concurrency level of 4, two priority queues and schedules a task on the first queue:

QueuedTaskScheduler qts = new QueuedTaskScheduler(TaskScheduler.Default,4);
TaskScheduler pri0 = qts.ActivateNewQueue(priority: 0);
TaskScheduler pri1 = qts.ActivateNewQueue(priority: 1);

Task.Factory.StartNew(()=>{ }, 
                      CancellationToken.None, 
                      TaskCreationOptions.None, 
                      pri0);

Leave a Comment