Problem
I’m a novice when it comes to parallel programming. Task and Thread are the two classes accessible in.NET.
So, here are my inquiries:
Asked by Jacek
Solution #1
A thread is a lower-level concept: if you start a thread directly, you know it will be a separate thread rather than running on the thread pool, and so on.
However, task is more than simply an abstraction for “where to run some code” – it’s really just “the promise of a future result.” As an illustration, consider the following:
It’s worth noting that the TaskT> abstraction is critical to C# 5’s async functionality.
In general, I’d advise you to use the higher level abstraction wherever possible: in modern C# code, directly starting your own thread should be rare.
Answered by Jon Skeet
Solution #2
Task is usually thought to be a higher-level concept than thread, and that is exactly what this statement means:
That is sufficient to make a decision. If you need to enable Cancel functionality while contacting a legacy API that tends to hang (for example, a timeoutless connection), then Thread is supported in this scenario. Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually – stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive – Task Parallel Library (TPL) .
Answered by Roman Pokrovskij
Solution #3
In Windows, the Thread class is used to create and manipulate threads.
A Task is an asynchronous operation that is part of the Task Parallel Library, which is a set of APIs for asynchronous and parallel task execution.
Using the Thread class was once one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), but it was cumbersome and had several drawbacks, not least of which was the performance overhead of creating a new thread to perform a background task.
Tasks and the TPL are now a lot better answer 90% of the time because they provide abstractions that allow for much more efficient use of system resources. I think there are a few cases where you want precise control over the thread on which your code runs, but in general, if you want to run something asynchronously, the TPL should be your first port of call.
Answered by Justin
Post is based on https://stackoverflow.com/questions/13429129/task-vs-thread-differences