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.
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:
Task.Factory.StartNew
, or ThreadPool.QueueUserWorkItem
, both will use the same threadpool (.NET 4.0)Task
or "raw" Threads, each timeslice will cause a context switch. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With