Search code examples
c#lambda

The proper way to end a BeginInvoke?


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);

Solution

  • 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.