Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task Thread Context Switches

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.

like image 496
TheWommies Avatar asked Dec 04 '11 21:12

TheWommies


1 Answers

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:

  • Difference between TPL and Threadpool, and the change threadpool in .NET 4.0: http://www.danielmoth.com/Blog/New-And-Improved-CLR-4-Thread-Pool-Engine.aspx

  • Shows how to implement a WorkStealingQueue in C#: http://www.bluebytesoftware.com/blog/2008/08/12/BuildingACustomThreadPoolSeriesPart2AWorkStealingQueue.aspx

  • A short version of daniel moth's blog post: http://blogs.msdn.com/b/jennifer/archive/2009/06/26/work-stealing-in-net-4-0.aspx

like image 104
ebb Avatar answered Sep 29 '22 15:09

ebb