13

I recently read this thread on MSDN. So I was thinking of using a lambda expression as a way of calling EndInvoke just as a way to make sure everything is nice and tidy. Which would be more correct?

example 1:

Action<int> method = DoSomething;

method.BeginInvoke(5, (a)=>{method.EndInvoke(a);}, null);

Example 2:

Action<int> method = DoSomething;

method.BeginInvoke(5, (a)=>
                                  {
                                      Action<int> m = a.AsyncState as Action<int>;
                                      m.EndInvoke(a);
                                  }, method);
Romano Zumbé
  • 7,735
  • 4
  • 32
  • 52
Mike_G
  • 15,551
  • 12
  • 67
  • 98

3 Answers3

13

I don't know if this was possible way back in Jan '09, but certainly now you can just write this:

method.BeginInvoke(5, method.EndInvoke, null);
Marcelo Cantos
  • 174,413
  • 38
  • 319
  • 360
12

Your 2nd example is slightly more efficient because the "method" delegate instance doesn't have to be captured in the closure. I doubt you'd ever notice.

Hans Passant
  • 897,808
  • 140
  • 1,634
  • 2,455
6

You might want to read this thread on Haacked's blog. Haven't had a chance to test it, but the gist is in one of the last lines:

ThreadPool.QueueUserWorkItem(callback => im.Send(to, from, subject, body));
Boris Callens
  • 86,820
  • 84
  • 205
  • 301
  • I actually have read that article, and it seems kind of redundant to use the QueueUserWorkItem if you can pass in a lambda in the call to BeginInvoke. – Mike_G Jan 12 '09 at 15:44
  • QueueUserWorkItem can provide other advanced thread pool management features besides calling EndInvoke. It is preferred to use that. – configurator Jan 12 '09 at 16:09
  • 1
    It depends on what you are using for. In IIS environment using ThreadPool will use the same threads that are available for request processing. http://stackoverflow.com/questions/1453283/threadpool-in-iis-context – Eugeniu Torica Sep 26 '12 at 08:31