Threads vs Tasks in C#

4:10 PM

Today my point of interest is Thread vs Task. Finally i had a little amount of time between projects to dive deeper in order to "examine" the difference. Actually when you ask people what is the difference you hear a lot of different things but the feeling that this point is not organized enough for me. So i decided to clarify this point once and for all :)

Threads
Threads are real OS thread with own its stack and resources. Threads allow to developer be fully controlled (by using Resume(), Suspend() or Abort() and etc). The problem is that threads are "time hungry" entities, which means that they will consume non trivial time at creation stage. In additional we should take in consideration time for context switching overhead performed by CPU.

ThreadPool
ThreadPool is entity that optimize overheads of the threads and it manage them [threads] by itself. In return it gives developer small maneuver possibilities such as pool size and ability to submit work to execute at some point. And thats it!

Task
Task is class introduces as part of TPL [Task Paralel Library] and it came with CLR 4.0.  Task represent compromise of above cases. It relays on TaskScheduler which in his turn working against ThreadPool.

Task able to return result after it completes (unlike ThreadPool). In addition we can run another task immediately when first one is completes.

Example:
Task<int> t = Task.Run(() => 2)
                              .ContinueWith((i) => i.Result * 2);

In this case when first task will be completed, the second task will be initiated and executed.
It's important to mentioned that each time when task is created, it lays on thread delivered by ThreadPool.

Here we can see that we might have issue with long run operations, since if we don't have enough free threads within ThreadPool - we may stuck when we would like to create new task. In order to avoid this issue, use TaskCreationOptions that can specify LongRunning property which means suggests to the scheduler to dedicate a thread to the task.

There are a lot of interesting facts about Tasks but i feel that i can not cover them all in this post. I believe that i will continue to write about my research in my future posts.

You Might Also Like

0 comments.

Popular Posts

Total Pageviews