Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any scenario where Tasks should not be used?

I am reading about Tasks been preferred way of doing async programming with 4.0. I am just wondering if there are any use cases where use of Tasks should not be preferred over normal c# threads?

like image 956
imak Avatar asked Oct 06 '12 15:10

imak


Video Answer


2 Answers

Since Tasks use the underlying ThreadPool (unless marked as long running), it's a bad idea to use them whenever using a ThreadPool is not advised e.g.

  • long I/O operations that clog the task queue and prevent other tasks from being executed.
  • doing operations that require thread identity such as setting affinity.
like image 138
Tudor Avatar answered Oct 13 '22 16:10

Tudor


This is gone into detail over here: Should I notice a difference in using Task vs Threads in .Net 4.0?

This biggest difference is that the TaskFactory uses thread pooling, so if you have a lot of tasks they may not start immediately. They have to wait for a free thread to run. In most cases this is acceptable..

Threads will run instantly as soon as .Start() is called, hardware permitting.

Assuming Thread pooling is okay, Tasks offer many benefits including cancellation, ContinueWith, OnSuccess, OnError, Exception aggregation, and WaitAll to name a few off the top of my head.

like image 32
Dharun Avatar answered Oct 13 '22 16:10

Dharun