Question

I was reading around and read that if I use Tasks instead of Threads in .Net they would not be susceptible to Context Switches that Threads have issues with.

However reading around I also noticed that Tasks just use Threads under the covers anyway.

So I am a bit confused, any clarification is appreciated.

Was it helpful?

Solution

What you've read is wrong.

Task is part of the TPL. The TPL uses a more advanced scheduler, than the CLR's threadpool. An example is that the TPL scheduler uses WorkStealingQueues.

A few facts:

  • Whether you do Task.Factory.StartNew, or ThreadPool.QueueUserWorkItem, both will use the same threadpool (.NET 4.0)
  • Whether you use a Task or "raw" Threads, each timeslice will cause a context switch.
  • Also if a higher priority thread becomes runnable it will cause a context switch.
  • A Task will cause just as many context switches as a regular thread.

Note that a context switch, only occurs if there aren't enough processors to handle the threads simultaneously.

Some links to check out:

OTHER TIPS

Context switches are not inherent in threads, they're inherent in misuse of threads. Tasks use threads in such a way that whatever thread happens to be running can take whatever task needs to be done, avoiding the expensive context switches that occur when threads are misused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top