Task.Run vs ThreadPool.QueueUserWorkItem

Not an expert on topics. I am trying to understand more about the asynchronous world available in .NET. Task.Run and ThreadPool.QueueUserWorkItem allow you to send work by the thread of the pool, but what are the differences or, if you want, the pros and cons of the two? Below is a list of my pros. Not sure if it is complete or even correct.

ThreadPool.QueueUserWorkItem pros:

  • The ability to pass an argument

Task.Run pros:

  • Ability to provide CancellationToken
  • Ability to wait for task completion
  • Ability to return a value to the calling code
+6
source share
2 answers

ThreadPool.QueueUserWorkItem is just the old version (introduced in .NET 1.1) that does the same job as Task.Run (introduced in .NET 4.5).

Microsoft is trying to avoid backward compatibility issues in .NET. Something written for .NET 1.1 can be compiled and run in .NET 4.5 with (usually) unchanged. Breaking changes usually comes from changes to the compiler, rather than changes to the framework, such as a variable declared in foreach used inside lambada, which behaves differently in C # 5 and newer .

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

One final point: ironically, it all ended in a full circle with HostingEnvironment.QueueBackgroundWorkItem(...) . This allows you to run something in the background thread in an ASP.NET environment and allow you to notify the background image of the AppDomain disconnected by the web server (which can often occur over a long period of inactivity).

+9
source

The only difference I recently realized between ThreadPool.QueueUserWorkItem and Task.Run is the way they handle exceptions.

If an unhanded exception occurs inside ThreadPool.QueueUserWorkItem and is not handled by the global exception handler, the parent thread will crash. On the other hand, unused exceptions from the Task.Run thread Task.Run not propagate unless you await or Task.Wait .

0
source

All Articles