I'm new to parallel programming. There are two classes available in .NET: Task
and Thread
.
So, my questions are:
Thread
over Task
(and vice-versa)?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.
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.
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).
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 .
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 futureWebClient.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)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.
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