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);
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Mike_G
  • 16,237
  • 14
  • 70
  • 101

3 Answers3

13

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
  • 922,412
  • 146
  • 1,693
  • 2,536
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
  • 181,030
  • 38
  • 327
  • 365
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
  • 90,659
  • 85
  • 207
  • 305
  • 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