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

Source: Internet
Author: User

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

Copy CodeThe code is as follows:
public delegate int AddHandler (int a,int b);
public class addition class
{
public static int Add (int a, int b)
{
Console.WriteLine ("Start calculation:" + A + "+" + B);
Thread.Sleep (3000); Simulates the method running for three seconds
Console.WriteLine ("Calculation done! ");
return a + 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.

Copy CodeThe code is as follows:
public class synchronous invocation
{
static void Main ()
{
Console.WriteLine ("===== Synchronous call Syncinvoketest =====");
AddHandler handler = new AddHandler (addition class. ADD);
int result = handler. Invoke (1, 2);
Console.WriteLine ("Keep doing something else ... ");
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.

Copy CodeThe code is as follows:
public class asynchronous invocation
{
static void Main ()
{
Console.WriteLine ("===== Asynchronous call Asyncinvoketest =====");
AddHandler handler = new AddHandler (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 ("Keep doing something else ... ");
The asynchronous Operation returns
Console.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.

Copy CodeThe code is as follows:
public class asynchronous callback
{
static void Main ()
{
Console.WriteLine ("===== Asynchronous callback Asyncinvoketest =====");
AddHandler handler = new AddHandler (addition class. ADD);
Asynchronous operator interface (note the different BeginInvoke methods!) )
IAsyncResult result = handler. BeginInvoke (1,2,new AsyncCallback (callback function), "Asycstate:ok");
Console.WriteLine ("Keep doing something else ... ");
Console.readkey ();
}

        static void callback function (IAsyncResult result)
         {    
             //result is "additive 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.

Problem:

(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. For example:

Copy CodeThe code is as follows:
static void Addcomplete (IAsyncResult result)
{
AddHandler handler = (AddHandler) result. asyncstate;
Console.WriteLine (handler. EndInvoke (result));
}

The complete code is as follows:

Copy CodeThe code is as follows:


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Runtime.Remoting.Messaging;
Namespace Consoletest
{
public delegate int AddHandler (int a,int b);
public class addition class
{
public static int Add (int a, int b)
{
Console.WriteLine ("Start calculation:" + A + "+" + B);
Thread.Sleep (3000); Simulates the method running for three seconds
Console.WriteLine ("Calculation done! ");
return a + B;
}
}

public class synchronous invocation
{
static void Main ()
{
Console.WriteLine ("===== Synchronous call Syncinvoketest =====");
AddHandler handler = new AddHandler (addition class. ADD);
int result = handler. Invoke (1, 2);

Console.WriteLine ("Keep doing something else ... ");
Console.WriteLine (result);
Console.readkey ();
}
}

public class asynchronous invocation
{
static void Main ()
{
Console.WriteLine ("===== Asynchronous call Asyncinvoketest =====");
AddHandler handler = new AddHandler (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 ("Keep doing something else ... ");
The asynchronous Operation returns
Console.WriteLine (handler. EndInvoke (result));
Console.readkey ();
}
}

public class asynchronous callback
{
static void Main ()
{
Console.WriteLine ("===== Asynchronous callback Asyncinvoketest =====");
AddHandler handler = new AddHandler (addition class. ADD);
Asynchronous operator interface (note the different BeginInvoke methods!) )
IAsyncResult result = handler. BeginInvoke (1,2,new AsyncCallback (callback function), "Asycstate:ok");
Console.WriteLine ("Keep doing something else ... ");
Console.readkey ();
}

        static void callback function (IAsyncResult result)
         {    
             //result is "additive class." The return value of the ADD () method
           //asyncresult is an implementation class for the IAsyncResult interface, reference 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);
       }
   }
}

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.