Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The proper way to end a BeginInvoke?

Tags:

c#

lambda

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);
like image 293
Mike_G Avatar asked Jan 12 '09 15:01

Mike_G


People also ask

How does BeginInvoke work?

The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes.

Whats up with BeginInvoke?

What does BeginInvoke do? According to MSDN, Control. BeginInvoke "Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on". It basically takes a delegate and runs it on the thread that created the control on which you called BeginInvoke .

Why use BeginInvoke c#?

BeginInvoke() is used to initiate the asynchronous call of the method. It has the same parameters as the function name, and two additional parameters. BeginInvoke() returns immediately and does not wait for the asynchronous call to complete. BeginInvoke() returns an IAsyncResult object.

How do you use EndInvoke and Startinvoke?

The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.


1 Answers

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);
like image 164
Marcelo Cantos Avatar answered Sep 28 '22 09:09

Marcelo Cantos