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