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:
Task.Run pros:
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With