What's the difference between QueueUserWorkItem() and BeginInvoke(), for performing an asynchronous activity with no return types needed

前端 未结 6 1975
甜味超标
甜味超标 2020-12-01 01:23

Following on from my BeginInvoke()/EndInvoke() question, are there major differences in performance/anything else between Delegate.BeginInvoke() and using QueueUserWorkItem(

6条回答
  •  忘掉有多难
    2020-12-01 01:42

    The main thing I can think of with QueueUserWorkItem is that you have to use the WaitCallback delegate type, which looks tricky if you already have a SomeRandomDelegate instance and some args. The good news is that you can fix this with a closure:

    ThreadPool.QueueUserWorkItem(
        delegate { someDelegate(arg1, arg2); }
    );
    

    This pattern also ensures you get proper strong typing at compile time (unlike passing an object state arg to QueueUserWorkItem and casting it in the target method). This pattern can also be used when calling methods directly:

    ThreadPool.QueueUserWorkItem(
        delegate { SomeMethod(arg1, arg2); }
    );
    

    Obviously, without an EndInvoke equivalent, you also can't get a return value back out unless you call a method / raise an event / etc at the end of your method... on a related note, you need to be careful with exception handling.

提交回复
热议问题