Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task vs Thread differences [duplicate]

I'm new to parallel programming. There are two classes available in .NET: Task and Thread.

So, my questions are:

  • What is the difference between those classes?
  • When is it better to use Thread over Task (and vice-versa)?
like image 286
Jacek Avatar asked Nov 17 '12 08:11

Jacek


People also ask

What is the difference between task vs thread which one is better?

Differences Between Task And ThreadThe Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.

Why are tasks better than threads?

It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread. Task supports cancellation through the use of cancellation tokens.

What is the difference between a task process and thread?

A task is a set of program instructions that are loaded in memory. Process and threads are related but otherwise orthogonal concepts. A thread is what the CPU actually runs; it's about scheduling access to shared resources (e.g. the CPU).

Does task run create new thread?

Note: Just using a Task in . NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the .


1 Answers

Thread is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.

Task is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:

  • Task.Delay doesn't need any actual CPU time; it's just like setting a timer to go off in the future
  • A task returned by WebClient.DownloadStringTaskAsync won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)
  • A task returned by Task.Run() really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.

Note that the Task<T> abstraction is pivotal to the async support in C# 5.

In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.

like image 66
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet