DEV Community

Cover image for Task Vs Thread ( C#)
aburra12
aburra12

Posted on

Task Vs Thread ( C#)

Notes gathered from different sources:

System threads are nothing but resources for tasks

Key differences between Task and Thread

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay)

Code sample for Cancellation Tokens in my github repo : https://github.com/aburra12/TaskCancellation

  1. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

But you get two new tools:

a) continuations

// continuation with ContinueWhenAll - execute the delegate, when ALL
// tasks[] had been finished; other option is ContinueWhenAny

Task.Factory.ContinueWhenAll( 
   tasks,
   () => {
       int answer = tasks[0].Result + tasks[1].Result;
       Console.WriteLine("The answer is {0}", answer);
   }
);
Enter fullscreen mode Exit fullscreen mode

b) nested/child tasks
//StartNew - starts task immediately, parent ends whith child

var parent = Task.Factory.StartNew
(() => {
          var child = Task.Factory.StartNew(() =>
         {
         //...
         });
      },  
      TaskCreationOptions.AttachedToParent
);
Enter fullscreen mode Exit fullscreen mode
  1. The task can return a result. There is no direct mechanism to return the result from a thread.

  2. A task can have multiple processes happening at the same time. Threads can only have one task running at a time.

  3. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.

How to create a Task

static void Main(string[] args) {  
    Task < string > obTask = Task.Run(() => (  
        returnβ€œ Hello”));  
    Console.WriteLine(obTask.result);  
} 
Enter fullscreen mode Exit fullscreen mode

How to create a Thread

static void Main(string[] args) {  
    Thread thread = new Thread(new ThreadStart(getMyName));  
    thread.Start();  
}  
public void getMyName() {} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)