Delegate .BeginInvoke vs. ThreadPool.QueueWorkerUserItem

public void BeforeSendReply(ref Message reply, object correlationState) { var replyCopy = reply; ThreadPool.QueueUserWorkItem(delegate { RequestQueueHandler.RequestQueue.Add((Message)correlationState, replyCopy); }); } 

against

  private delegate void RequestQueueHandlerAdd(Message request, Message reply); private static void AsyncMethod(Message request, Message reply) { RequestQueueHandler.RequestQueue.Add(request, reply); } public void BeforeSendReply(ref Message reply, object correlationState) { ((RequestQueueHandlerAdd)AsyncMethod).BeginInvoke((Message)correlationState, reply, null, null); } 

which of these two should i use? (which works better?) why?
Does my method overhead affect the decision, or is one of these implementations always superior to the other?
for what reason?

I'm prone to ThreadPool.QueueWorkerUserItem, but I have no idea which one is really better, neither in this case, nor at all

UPDATE

I read something about TPL .. did this:

  public void BeforeSendReply(ref Message reply, object correlationState) { var replyCopy = reply; var enqueue = Task.Factory.StartNew(() => RequestQueueHandler.RequestQueue.Add((Message)correlationState, replyCopy)); } 

how should i handle the exception here? I mean, if I do

  public void BeforeSendReply(ref Message reply, object correlationState) { var replyCopy = reply; var enqueue = Task.Factory.StartNew(() => RequestQueueHandler.RequestQueue.Add((Message) correlationState, replyCopy)); **try { enqueue.Wait(); } catch(AggregateException e) { Handle(e); }** } 

I did not miss the whole point of parallelism here?

Should I just handle the possible RequestQueueHandler.RequestQueue.Add exception in the RequestQueueHandler.RequestQueue.Add method?

+6
source share
3 answers

Asynchronous delegates give you a bit more: return values ​​and throwing exceptions (you must call EndInvoke to access them). Using ThreadPool directly, you must take care of this yourself.

The advantage of ThreadPool on the other hand is simplicity.

Take a look at this great online version that details two (or more) approaches.

Typically thumb:

  • use TPL if you can
  • if you don't use ThreadPool directly for simple fire and forget tasks
  • if you do not use async delegates
+2
source

The Delegate.BeginInvoke() method also uses ThreadPool, so do not expect any significant performance difference.

QueueUserWorkItem() not much better, easiest in most cases.

But note that both samples are missing. Error processing.
Your good short delegates need try / catch, the BeginInvoke script is a callback.

Therefore, when you can use Fx4, you should use TPL for a much higher level of abstraction.

+3
source

ThreadPool.QueueWorkerUserItem is higher and preferred. But ThreadPool.QueueWorkerUserItem behind the scene uses Delegate.BeginInvoke . But Delegate.BeginInvoke uses threads from ThreadPool .

+1
source

Source: https://habr.com/ru/post/886268/


All Articles