Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am currently using the LimitedConcurrencyLevelTaskScheduler detailed here http://msdn.microsoft.com/en-us/library/ee789351.aspx

I want to enhance this so that individuals tasks can be assigned priority. These priorities need not map to thread priority. It should only influence the order in which tasks are started.

Does anyone know of an example of such a task scheduler? (a lot of the scheduling stuff is over my head so it would be great if there was an existing solution)

like image 441
Rezler Avatar asked Feb 16 '12 17:02

Rezler


2 Answers

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);
like image 88
Panagiotis Kanavos Avatar answered Oct 05 '22 11:10

Panagiotis Kanavos


Use some sorted or priority data structure for the task list. Then create your own add that takes in the Priority. This may not be as good as others but it will prioritize Tasks List. You can reuse 99% of the code there. Simply replace LinkedList with a Sorted list or use LINQ to sort and write a method add that takes the priority.

like image 24
Brad Semrad Avatar answered Oct 05 '22 12:10

Brad Semrad