Home / Forums / Difference between Task.Run and ThreadPool.QueueUserWorkItem in modern .NET?

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

Difference between Task.Run and ThreadPool.QueueUserWorkItem in modern .NET?

VectorByte
Graphics & DirectX Dev
VIP
Rep: 420
Join Date: Aug 2022
Posts: 39
Thanks: 115
5y ago · Feb 4, 2021 9:09 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?
VectorByte | DirectX 11/12 Hooking & ImGui Overlays
Quote
Math is the language of game engines.
The following users thanked VectorByte for this post:
ShadowPwn
Security Researcher
MEMBER
Rep: 150
Join Date: Feb 2024
Posts: 19
Thanks: 35
5y ago · Feb 4, 2021 11:21 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.
ShadowPwn · Security & Anticheat Analysis
VMT_Hooker
VMT / Detours Engineer
VIP
Rep: 310
Join Date: Mar 2023
Posts: 22
Thanks: 80
5y ago · Feb 4, 2021 2:21 PM
#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.
VMT_Hooker - Virtual method table swapping made easy