asynchronous invocation of a delegate
Sometimes, if you want a delegate to complete a complex time-consuming task, the synchronous call is not a good choice because the user is faced with a tedious time consuming and lengthy ( Comparatively speaking ) of waiting. In this case, the asynchronous invocation of the delegate shows an advantage, and the asynchronous call to C # for the delegate is also encapsulated, through BeginInvoke and endinvke to complete. An example is given below.
1. Define a delegate,mydelegate
2. defines an event for an external subscription
3. Increment, test field
4. doIt method, each time the increment will be increased, the value of 5 , the event is called asynchronously
The focus is on this code:
IAsyncResult result = This.callBack.BeginInvoke (new AsyncCallback ( (IA) = { MessageBox.Show (" Completed "); AsyncResult ar = (AsyncResult) ia; MyDelegate MD = AR. AsyncDelegate as MyDelegate; int r = Md. EndInvoke (IA); MessageBox.Show (r.tostring () + IA. asyncstate); }), "message"); MessageBox.Show ("Begin Invoke");
BeginInvoke The function consists of four parameters:
AsyncCallback object: This parameter means, tell it what to do next when the callback is complete, and therefore need to pass it a method. New AsyncCallback ( A method is received here, I use a lambda expression here ).
Object object: The argument to be passed to the method called at the end of the callback.
AsyncResult ar = (AsyncResult) ia; Get incoming IasyncResult, convert to AsyncResult Object
mydelegate md = ar. AsyncDelegate as MyDelegate; get callBack Object
int r = Md. EndInvoke (IA); ends the invocation of the delegate, obtains the return value
MessageBox.Show (r.tostring () + ia. asyncstate);//// Verify that the return value is taken
OK , now that the asynchronous delegate has been defined, the next step is to call:
Code Description:
New a Timer and a asyntronisedelegate object.
Subscribe CallBack event, Method Finally, returns a 1 .
with Timer Complete Increment cumulative operation, cumulative per second 1 .
when Increment accumulate to 5 the time, Callback event is triggered, it is time to perform a complex task that loops through the Ten billions of times.
after running, you will see the Prompt box, followed by the , about the 2-3 seconds Prompt box appears, and then the and the(visible, at the end of the asynchronous call, we succeeded in getting the return value of the method)
The above is the contents of the code sample for the asynchronous invocation of C # delegate, please follow topic.alibabacloud.com (www.php.cn) for more information!