Three invocation examples of C # delegates (synchronous calls asynchronous callbacks are invoked asynchronously)

Source: Internet
Author: User

This article will explain the differences and pros and cons of executing the same addition class with the delegate, mainly through synchronous invocation, asynchronous invocation, asynchronous callback, three examples.

First, the code defines a delegate and the following three examples of the method that will be called:

 Public Delegate intAddHandler (intAintb); Public classAddition class { Public Static intADD (intAintb) {Console.WriteLine ("Start calculation:"+ A +"+"+b); Thread.Sleep ( the);//simulates the method running for three secondsConsole.WriteLine ("calculation done! "); returnA +b; }
}

Synchronous invocation

The Invoke method of the delegate is used for synchronous invocation. A synchronous call can also be called a blocking call, which blocks the current thread and then executes the call, and then continues down after the call is complete. The code is as follows

 Public classSynchronous Call {Static voidMain () {Console.WriteLine ("===== Synchronous Call Syncinvoketest ====="); AddHandler Handler=NewAddHandler (addition class.            ADD); intresult = handler. Invoke (1,2); Console.WriteLine ("continue to do other things ... ");            Console.WriteLine (result);        Console.readkey (); }      }

Synchronous calls can block threads, and if you are invoking a heavy workload (such as a large number of IO operations), it can cause the program to pause for a long time, creating a bad user experience, which is necessary for an asynchronous invocation.

asynchronous invocation

Instead of blocking the thread, the asynchronous call plugs the call into the thread pool, which the program's main thread or UI thread can continue to execute. The asynchronous invocation of a delegate is implemented by BeginInvoke and EndInvoke. The code is as follows:

 Public classAsynchronous Call {Static voidMain () {Console.WriteLine ("===== Asynchronous Call Asyncinvoketest ====="); AddHandler Handler=NewAddHandler (addition class.            ADD); //IAsyncResult: Asynchronous Operation Interface (interface)//BeginInvoke: The start of an asynchronous method for a delegate (delegate)IAsyncResult result = handler. BeginInvoke (1,2,NULL,NULL); Console.WriteLine ("continue to do other things ... "); //The asynchronous operation returnsConsole.WriteLine (handler.            EndInvoke (result));        Console.readkey (); }}

As you can see, the main thread does not wait, but it runs down directly. However, the problem persists when the main thread runs to EndInvoke, and if the call is not ended (which is likely to occur), then the threads will still be blocked in order to wait for the result to be called.

Asynchronous delegate, or you can refer to the following notation:

action<object> action= (obj) =>method (obj);

Action. BeginInvoke (obj,ar=>action. EndInvoke (AR), null);

You can complete an operation in two simple sentences.

Asynchronous callbacks

With the callback function, the callback function is automatically invoked at the end of the call, which solves the situation where the thread is still blocked waiting for the result to be called. The code is as follows:

 Public classAsynchronous Callback {Static voidMain () {Console.WriteLine ("===== Asynchronous callback Asyncinvoketest ====="); AddHandler Handler=NewAddHandler (addition class.            ADD); //Asynchronous Operator Interface (note the different BeginInvoke methods!) )IAsyncResult result = handler. BeginInvoke (1,2,NewAsyncCallback (callback function),"Asycstate:ok"); Console.WriteLine ("continue to do other things ... ");        Console.readkey (); }        Static voidcallback function (IAsyncResult result) {//result is the "addition class." The return value of the ADD () method//AsyncResult is an implementation class for the IAsyncResult interface, Space: System.Runtime.Remoting.Messaging//The AsyncDelegate property can be cast to the actual class of a user-defined delegate. AddHandler handler =( AddHandler) ((AsyncResult) result).            AsyncDelegate; Console.WriteLine (handler.            EndInvoke (result)); Console.WriteLine (Result.        asyncstate); }}

The type of delegate I define is AddHandler, and in order to access Addhandler.endinvoke, you must cast the asynchronous delegate to AddHandler. You can call Maddhandler.endinvoke in an asynchronous callback function (type AsyncCallback) to get the result of the Addhandler.begininvoke that was originally submitted.

Attention:

(1) int result = handler. Invoke ();

Why is the parameter and return value of invoke the same as the AddHandler delegate?

Answer: The parameters of the Invoke method are simple, a delegate, a parameter table (optional), and the main function of the Invoke method is to help you invoke the method specified by the delegate on the UI thread. The Invoke method first checks that the calling thread (that is, the current thread) is not the UI thread, and if so, directly executes the method that the delegate points to, if it is not, it switches to the UI thread and then executes the method that the delegate points to. If the current thread is not a UI thread, invoke blocks until the method that the delegate points to executes, and then switches back to the thread that issued the call (if necessary).

So the arguments and return values of the Invoke method should be consistent with the invocation of his delegate.

(2) IAsyncResult result = handler. BeginInvoke (1,2,null,null);

BeginInvoke: Begins an asynchronous request, invokes a thread in the thread pool to execute,

Returns the IAsyncResult object (the core of the async). IAsyncResult simply says that he stores an interface for the state information of an asynchronous operation, and can also use him to end the current asynchronous.

Note: BeginInvoke and EndInvoke must be called in pairs. Even if the return value is not required, EndInvoke must still be called, which may cause a memory leak.

(3) IAsyncResult.AsyncState properties:

Gets a user-defined object that qualifies or contains information about an asynchronous operation.

Reprint: http://www.jb51.net/article/44093.htm

Three invocation examples of C # delegates (synchronous calls asynchronous callbacks are invoked asynchronously)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.