Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Run vs ThreadPool.QueueUserWorkItem

Not a subject expert I'm trying to understand more of the async world available in .NET. Task.Run and ThreadPool.QueueUserWorkItem both allow dispatching work on a pool thread but what are the differences or, if you prefer, pros and cons of the two? Following is my list of pros. Not sure if it is complete or even correct.

ThreadPool.QueueUserWorkItem pros:

  • Possibility of passing an argument

Task.Run pros:

  • Possibility of providing a CancellationToken
  • Possibility of waiting Task completion
  • Possibility of returning a value to calling code
like image 673
Stefano Avatar asked Aug 10 '16 18:08

Stefano


People also ask

When should you not use ThreadPool?

Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.

Does Task use ThreadPool?

By default, TPL types like Task and Task<TResult> use thread pool threads to run tasks. You can also use the thread pool by calling ThreadPool.

What is ThreadPool QueueUserWorkItem?

QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

What is the difference between thread thread pool and TPL?

Thread-Pool pattern states, the work items are queued and the free threads in thread pool takes one from this queue. TPL however store the items (tasks) to queues of threads and work-stealing works if needed... Thus, quite differently.


1 Answers

ThreadPool.QueueUserWorkItem is just the older implementation (introduced in .NET 1.1) of doing the same job as Task.Run (introduced in .NET 4.5).

Microsoft tries to avoid breaking backwards compatibility in .NET. Something written for .NET 1.1 can be compiled and ran in .NET 4.5 with (usually) no changes. Breaking changes are usually from compiler changes, not framework changes, like the variable declared in a foreach used inside a lambada behaving differently in C# 5 and newer.

There is no real reason to use ThreadPool.QueueUserWorkItem when you have Task.Run.

One ending point: ironically, things have actually come full circle with HostingEnvironment.QueueBackgroundWorkItem(...). It lets you run something on a background thread in a ASP.NET environment and let the background work be notified of AppDomain shutdowns by the web server (which can frequently happen during long periods of inactivity).

like image 95
Scott Chamberlain Avatar answered Sep 19 '22 03:09

Scott Chamberlain