Home / Forums / Difference between Task.Run and ThreadPool.QueueUserWorkItem in modern .NET? [Discussion #9]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

Difference between Task.Run and ThreadPool.QueueUserWorkItem in modern .NET? [Discussion #9]

CodeRefactorer
Software Architect
MEMBER
Rep: 296
Join Date: Feb 2021
Posts: 6
Thanks: 21
5y ago · Feb 22, 2021 8:21 AM
#1
Is there any real performance difference between Task.Run and ThreadPool.QueueUserWorkItem in .NET 8, or does Task.Run just wrap it with a Task object?
CodeRefactorer · Software Architect
Clean architecture, SOLID principles, and refactoring legacy...
The following users thanked CodeRefactorer for this post:
NullPtr_
Assembly & Engine Research
MEMBER
Rep: 260
Join Date: May 2023
Posts: 27
Thanks: 62
5y ago · Feb 22, 2021 10:52 AM
#2
Task.Run() uses the ThreadPool internally under the hood! The major advantage of Task.Run is that it returns a Task/Task<T> that supports async/await, cancellation tokens, continuation chaining with ContinueWith, and proper exception propagation. QueueUserWorkItem is lower level and harder to capture exceptions from.
NullPtr_ · 0xDEADBEEF was here
ApexPredator_
Source Engine Modder
VIP
Rep: 340
Join Date: May 2022
Posts: 23
Thanks: 88
5y ago · Feb 22, 2021 11:52 AM
#3
Unless you are building an ultra-low-overhead specialized scheduler where the 48-byte Task allocation is unacceptable, always use Task.Run for clean async code.
ApexPredator_ · Source Engine Specialist