a code like below will start a new thread to do the job. Is there any way I can control the priority of that thread?
Task.Factory.StartNew(() => {
// everything here will be executed in a new thread.
// I want to set the priority of this thread to BelowNormal
});
As others have mentioned, you need to specify a custom scheduler to go with your task. Unfortunately there isn't a suitable built-in scheduler.
You could go for the ParallelExtensionsExtras that Glenn linked to, but if you want something simple that can just be pasted right into your code, try the following. Use like this:
The code:
Notes:
MaximumConcurrencyLevel
,GetScheduledTasks
andTryExecuteTaskInline
.This is one of "not to do" when you decide whether to use thread pool or not ;-)
More details here: http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
So the answer is "No, you cannot specify particular priority for thread created in Theads Pool"
As of general threadings I bet you already know about Thread.Priority property
Thread priority for Tasks can be set inside the actual method that executes the Task. But don't forget to restore the priority once you are done to avoid problems.
So first start the Task:
new TaskFactory().StartNew(StartTaskMethod);
Then set the thread priority:
When changing the priority, keep in mind this: Why *not* change the priority of a ThreadPool (or Task) thread?
For setting priority with
Task
, check out the custom task schedulers described by Microsoft expert Stephen Toub in this MSDN blog post. For further detail, don't miss the links to the previous two posts that he mentions in the first sentence.For your issue, it sounds like you might want to look at the
QueuedTaskScheduler
.