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.
What you’ve read is wrong.
Taskis part of the TPL. The TPL uses a more advanced scheduler, than the CLR’s threadpool. An example is that the TPL scheduler usesWorkStealingQueues.A few facts:
Task.Factory.StartNew, orThreadPool.QueueUserWorkItem, both will use the same threadpool (.NET 4.0)Taskor “raw” Threads, each timeslice will cause a context switch.Taskwill 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