Why *not* change the priority of a ThreadPool (or Task) thread?

Glenn Slayden picture Glenn Slayden · Apr 8, 2011 · Viewed 12.1k times · Source

There are many places across the web and Stack Overflow where one is discouraged from changing the priority of a ThreadPool thread or TPL Task. In particular:

"You have no control over the state and priority of a thread pool thread."
"The runtime manages the thread pool. You have no control over the scheduling of the thread, nor can you change the thread's priority."

"You should not change the Culture or Priority or... of a PoolThread. Just like you don't paint or re-decorate a rental car."

"There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads: (such as...) You require a thread to have a particular priority."

"Each thread in ThreadPool runs at the default priority and the code to change the ThreadPriority has no effect."

However, it is a simple matter to do so, and the debugger shows that the change does seem to stick (insofar as the value can be read back).

Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

So the question is, what is the specific reason for this particular taboo?

My suspicion: doing so disturbs the delicate load balancing-assumptions of the pool. But this doesn't explain why some sources say that you can't change it.

Answer

Talljoe picture Talljoe · Apr 8, 2011

The thread pool, especially the .NET 4.0 thread pool, has many tricks up its sleeve and is a rather complicated system. Add in tasks and task schedulers and work stealing and all sorts of other things and the reality is you don't know what is going on. The thread pool may notice that your task is waiting on I/O and decide to schedule something quick on your task or suspend your thread to run something of higher priority. Your thread may somehow be a dependency for a higher-priority thread (that you may or may not be aware of) and end up causing a deadlock. Your thread may die in some abnormal way and be unable to restore priority.

If you have a long-running task such that you think it would be best that your thread have a lower priority then the thread pool probably isn't for you. While the algorithms have been improved in .NET 4.0, it is still best used for short-lived tasks where the cost of creating a new thread is disproportional to the length of the task. If your task runs for more than a second or two the cost of creating a new thread is insignificant (although management might be annoying).