How to schedule Task on different thread priority?
.NET 4 brought as the Task Parallel Library (TPL)
which is great improvement over the old threading
techniques, both in terms of API and performance.
the TPL APIs is elegant and clear, but intentionally
the TPL team didn’t add API (out of the box) for scheduling
thread under different priorities.
this post deal discuss how to create custom TPL scheduler that schedule the
work units under different thread priorities.
most of the TPL APIs expose overload with scheduler parameter.
out of the box TPL is having 2 schedulers:
- Default scheduler.
- synchronization context (Dispatcher) scheduler (for synchronizing work back into the
synchronization context like UI thread), see TaskScheduler.FromCurrentSynchronizationContext().
How can we change the behavior of the scheduler?
building custom scheduler involve with inheritance of TaskScheduler.
in our sample we will use BlockingCollection<Task> for having
thread safe consumer producer pattern which will consume work
under custom thread that run on specific priority.
TaskScheduler is having small amount of virtual and abstract methods:
the most important overrides is QueueTask which get
the task and responsible to schedule it execution.
in our implementation it enqueue the task into the producer consumer collection
and make sure that the worker threads is running.
the actual task execution is done by consuming tasks (under the worker thread)
and call base.TryExecuteTask(task), as shown in the following code snippet:
the custom scheduler can be inject into the TPL APIs as shown in the following snippets:
the sample compare execution of tasks with default and custom scheduler.
you may notice that thread that run under custom scheduler is also having thread name.
the output of the sample is look as follow:
the parallel team intentionally didn’t include priority scheduler for a good reason,
and most common execution should be avoid using such scheduler.
however there may be some special occasions which it might make sense
to use such scheduler, like:
- execution of debug level logger write under low priority in order to prevent it from compete upon CPU resources.
- execution test under controlled environment might take advantage of custom test scheduler.