When is the System.Threading.Task useful?
There are two main advantages in using Task
s:
-
Task
can represent any result that will be available in the future (the general concept is not specific to .Net and it's called future), not just a computation. This is especially important withasync
-await
, which usesTask
s for asynchronous operations. Since the operation that gets the result might fail,Task
s can also represent failures. -
Task
has lots of methods to operate on them. You can synchronously wait until it finishes (Wait()
), wait for its result (Result
), set up some operation when theTask
finishes (ContinueWith()
) and also some methods that work on severalTask
s (WaitAll()
,WaitAny()
,ContinueWhenAll()
). All of this is possible using other parallel processing methods, but you would have to do it manually.
And there are also some smaller advantages to using Task
:
- You can use a custom
TaskScheduler
to decide when and where will theTask
run. This can be useful for example if you want to run aTask
on the UI thread, limit the degree of parallelism or have aTask
-level readers–writer lock. -
Task
s support cooperative cancellation throughCancellationToken
. -
Task
s that represent computations have some performance improvements. For example, they use work-stealing queue for more efficient processing and they also support inlining (executingTask
that hasn't started yet on a thread that synchronously waits for it).
William
Updated on June 05, 2022Comments
-
William over 1 year
I have used most of the Threading library extensively. I am fairly familiar with creating new Threads, creating BackgroundWorkers and using the built-in .NET ThreadPool (which are all very cool).
However, I have never found a reason to use the Task class. I have seen maybe one or two examples of people using them, but the examples weren't very clear and they didn't give a high-level overview of why one should use a task instead of a new thread.
Question 1: From a high-level, when is using a task useful versus one of the other methods for parallelism in .NET?
Question 2: Does anyone have a simple and/or medium difficulty example demonstrating how to use tasks?
-
Keith Robertson about 9 years+1, excellent answer. However, I would consider "Smaller #1" to be a main advantage, and replace "custom" with "specific". There are two commonly used built-in TaskSchedulers, one for background tasks which can run on any ThreadPool thread, and one for code which must run in a specific SynchronizationContext, e.g. on a UI thread. Point 2: You need not write a custom scheduler for this feature to be useful. Point 1: It's a huge benefit that the same model can be used for foreground and background units of future work.
-
Jeb50 over 5 yearsA sophisticated concept answered in simple and plain English, hats-off!