Delegate.BeginInvoke vs ThreadPool.QueueWorkerUserItem
The Delegate.BeginInvoke()
method also uses the ThreadPool, so don't expect any meaningful difference in performance.
QueueUserWorkItem()
isn't directly better, just easier in most cases.
But note that both samples are missing Error handling.
Your nice short delegate needs a try/catch, the BeginInvoke scenario a Callback.
So when you can use Fx4 you ought to use the TPL for a much higher abstraction level.
Asynchronuous delegates give you a bit more: return values and exception forwarding (you should call EndInvoke to get access to them).By using ThreadPool directly you have to take care of that yourself.
ThreadPool's advantage on the other hand is simplicity.
Do have a look at this excellent online book, which discusses the two (and more) approaches in depth.
As a rule of a thumb:
- use TPL if you can
- if not use ThreadPool directly for simple fire-and-forget tasks
- if not use async delegates
ThreadPool.QueueWorkerUserItem
is higher level and preferred. But But ThreadPool.QueueWorkerUserItem
behind the scene uses Delegate.BeginInvoke
.Delegate.BeginInvoke
uses threads from the ThreadPool
.