Monday, 1 September 2014

Why should I use Tasks over standard multithreading?

1.      It is the way Microsoft is moving with regards to asynchrony and multithreading. For example, the all new ‘async’ and ‘await’ keywords use Tasks extensively.
2.      Tasks have been optimised to make use of the CLR thread pool, and so do not have the overhead associated with creating a dedicated thread using the Thread class. I think I am also correct in saying that the tweaking Microsoft have done on Tasks makes them more efficient than interacting with the thread pool via ThreadPool.QueueUserWorkItem().
3.      Tasks implement local work queues. This optimization allows you to efficiently create many quickly executing child tasks without incurring the contention overhead that would otherwise arise with a single work queue.
4.      You can wait on the completion of tasks without the use of signalling constructs (Monitor class etc).
5.      You can chain tasks together to execute one after the other.
6.      Is it just me, or is it just more logical to separate units of computationally intensive work into separate tasks, rather than working directly with threads? This is partly as a result of the higher level of abstraction that tasks provide.
7.      Adding continuations (Task.ContinueWith)
8.      Waiting for multiple tasks to complete (either all or any)
9.      Capturing errors in the task and interrogating them later
10.  Capturing cancellation (and allowing you to specify cancellation to start with)
11.  Potentially having a return value
12.  Using await in C# 5
13.  Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

No comments:

Post a Comment