Reputation: 5072
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.
Upvotes: 5
Views: 5028
Reputation: 9377
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
Upvotes: 11
Reputation: 182769
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.
Upvotes: 1