C #: synchronous calls, asynchronous calls, asynchronous callbacks

ylbtech-C #: synchronous calls, asynchronous calls, asynchronous callbacks

 

1. Back to top
1、

This article will explain in a moment to entrust with the implementation of a "class addition" of the differences and the pros and cons through three examples "synchronous call", "asynchronous call", "asynchronous callbacks."
 

First, the following three examples and methods to be invoked by a delegate code defines:


    int the AddHandler the delegate public (A int, int B);
    public class adder class
    {
        public static int the Add (A int, int B)
        {
            Console.WriteLine ( "Start calculation:" A + + "+" + B);
            the Thread. Sleep (3000); // the simulation method for operating three seconds
            Console.WriteLine ( "calculation is done!");
            return A + B;
        }
    }

 

 

Synchronous call

Invoke method used for the commission of a synchronous call. Synchronous call can also be called a blocking call, it blocks the current thread, then make the call, the call is completed and then continue down.

public class synchronous call
{
        static void the Main ()
        {
            Console.WriteLine ( "================ ================ synchronous call SyncInvokeTest");
            the AddHandler the AddHandler Handler = new new (class adder .Add);
            int Result = handler.Invoke (1, 2);

            Console.WriteLine ( "keep doing something else ...");

            Console.WriteLine (the Result);
            Console.ReadKey ();
        }
        
}

Synchronous call will block the thread, if it is to be called a lot of work (such as a large number of IO operations), may make the program pause for a long time, resulting in a poor user experience, this time an asynchronous call is very necessary.
 

 

Asynchronous call

Asynchronous call does not block the thread, but to call the stuffed thread pool, the program's main UI thread or threads can proceed.
Asynchronous delegate invocation is achieved by BeginInvoke and EndInvoke.
 

public class asynchronous call
{
        static void the Main ()
        {
            Console.WriteLine ( "asynchronous calls ================ ================ AsyncInvokeTest");
            the AddHandler the AddHandler Handler = new new (class adder .Add);

            // the IAsyncResult: asynchronous operation Interface (interface)
            // BeginInvoke: Begins an asynchronous method delegate (delegate) of
            IAsyncResult the Result = handler.BeginInvoke (1, 2, null, null);

            Console.WriteLine ( "keep doing something else ...");

            // asynchronous operation returns
            Console.WriteLine (handler.EndInvoke (Result));
            the Console.ReadKey ();
        }
        
}

We can see, the main thread did not wait, but directly run down.
But the problem still exists, when the main thread running to EndInvoke, if the time is not the end of the call (this situation is likely to occur), then to wait for the result of the call, the thread will still be blocked.
 

 Asynchronous delegates, reference may be written as follows:

Action<object> action=(obj)=>method(obj);
action.BeginInvoke(obj,ar=>action.EndInvoke(ar),null);

Simple sentence or two to complete an operation.
 

 

Asynchronous callbacks

Using a callback function, when the end of the call will automatically call the callback function to solve the wait for the result of the call, and let the thread is still blocked situation.

public class asynchronous callback
{
        static void the Main ()
        {
            Console.WriteLine ( "asynchronous callback ================ ================ AsyncInvokeTest");
            the AddHandler the AddHandler Handler = new new (class adder .Add);

            // asynchronous operation Interface ( ! Note BeginInvoke different methods)
            IAsyncResult the Result = handler.BeginInvoke (1, 2, new new AsyncCallback (callback function), "AsycState: the OK");
            
            Console.WriteLine ( "keep doing something else ...");
            Console. ReadKey ();
        }

        static void callback (IAsyncResult Result)
        {// Result is "addition type .Add () method" return value

            // AsyncResult is an implementation IAsyncResult interface space: System.Runtime.Remoting.Messaging
            // AsyncDelegate properties can be coerced to delegate actual user-defined classes.
            Handler = the AddHandler (the AddHandler) ((the AsyncResult) Result) .AsyncDelegate;
            Console.WriteLine (handler.EndInvoke (Result));
            Console.WriteLine (result.AsyncState);
        }
        
}

I define the type of commission is AddHandler, then in order to access AddHandler.EndInvoke, asynchronous delegate must be cast to AddHandler. MAddHandler.EndInvoke can call in an asynchronous callback function (of type AsyncCallback) in order to obtain AddHandler.BeginInvoke results originally submitted. 

 

problem:
 

(1) int result = handler.Invoke ( 1,2);
Why Invoke parameters and return values and AddHandler commission is the same?
A: The
parameter of Invoke method is simple, a commission, a parameter table (optional), and the main function is to help the Invoke method delegate method specified by your call on the UI thread. Invoke method first checks the thread (ie, the current thread) is not the calling UI thread, and if so, direct execution method delegate pointed, if not, it will switch to the UI thread, then execution method delegate pointed . Whether the current thread is not the UI thread, Invoke method will block until the commission completes points, and then switch back to the calling thread (if necessary), return.
So Invoke method parameters and return values and call his commission should be consistent.

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

BeginInvoke: an asynchronous start request, the calling thread pool to execute a thread,
returned IAsyncResult object (asynchronous core) IAsyncResult simply. an interface status information he stored asynchronous operation, you can also use it to end the current asynchronous.
Note: BeginInvoke and EndInvoke pairs must be called even if no return value, but still must call EndInvoke, as this may cause a memory leak.

 

(3) IAsyncResult.AsyncState properties:
obtaining a user-defined objects, which defines or comprises information about the asynchronous operation. E.g:

static void AddComplete(IAsyncResult result) 
{   
      AddHandler handler = (AddHandler)result.AsyncState;    
      Console.WriteLine(handler.EndInvoke(result)); 
      。。。。。
}

 

The complete code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadCallback
{
    class Program
    {

        public delegate int AddHandler(int a, int b, int c);

        public class AddClass
        {
            public static int Add(int a, int b, int c)
            {
                Console.WriteLine ( " \ n-counted: " + A + " + " + B + " + " + C);
                The Thread.Sleep ( 3000 ); // simulation method for operating the three seconds 
                Console.WriteLine ( " calculation is done! " );
                 Return A + B + C;
            }
        }

        ///  <the Summary> 
        /// synchronous call
         ///  </ the Summary> 
        public  class SynchronousCall
        {
            static void Main_S()
            {
                Console.WriteLine ( " ===== ===== synchronous call SyncInvokeTest " );
                AddHandler handler = new AddHandler(AddClass.Add);
                int result = handler.Invoke(1, 2, 3);

                Console.WriteLine ( " keep doing something else ... " );

                Console.WriteLine(result);
                Console.ReadKey();
            }

        }

        ///  <the Summary> 
        /// asynchronous call
         ///  </ the Summary> 
        public  class AsynchronousCall
        {
            static void Main_S()
            {
                Console.WriteLine ( " ===== ===== asynchronous calls AsyncInvokeTest " );
                AddHandler handler = new AddHandler(AddClass.Add);

                // the IAsyncResult: asynchronous operation of the interface (interface)
                 // BeginInvoke: Start an asynchronous method delegate (the delegate) of 
                the IAsyncResult handler.BeginInvoke Result = ( . 1 , 2 , . 3 , null , null );
                Console.WriteLine ( " ------ continue to do other things ... \ the n- " );

                // asynchronous operation returns 
                Console.WriteLine (handler.EndInvoke (result));
                Console.ReadKey();
            }

        }


        static void Main(string[] args)
        {

            Console.WriteLine ( " ===== ===== asynchronous callback AsyncInvokeTest " );
            AddHandler handler = new AddHandler(AddClass.Add);

            // asynchronous operation interface (CAUTION! BeginInvoke different methods) 
            the IAsyncResult handler.BeginInvoke Result = ( . 1 , 2 , . 3 , new new the AsyncCallback (CallbackFunc), " AsycState: the OK " );

            Console.WriteLine ( " ------ continue to do other things ...-------- " );
            Console.ReadKey();

        }

        static void CallbackFunc(IAsyncResult result)
        {
            // Result is "addition type .Add () method" return value             
             // the AsyncResult IAsyncResult is an implementation of the interface, reference space: System.Runtime.Remoting.Messaging             
             // AsyncDelegate delegate property can be cast to a user-defined The actual class. 
            Handler = the AddHandler (the AddHandler) ((the AsyncResult) Result) .AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }  

    }
}

 

2、
2. Return to top
1, multi-threaded example callback by value | C # multithreaded callback example by value
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System;
using System.Threading;
namespace DataImportFromAccess
{


    // declare a callback function: Note that the parameters passed to the function argument types Example consistent with class 
    public  the delegate  void ExampleCallback ( int lineCount, the Label LB);
     public  class the Form1 {
         public the Form1 ()
        {
            InitializeComponent();
        }

        public void CurrentNumber(int tempCurrent,Label lb)
        {
            lb.Text = tempCurrent.ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ThreadWithData twd = new ThreadWithData(1, 100,this.label1,new ExampleCallback(CurrentNumber));
            Thread td = new Thread(new ThreadStart(twd.RunMethod));
            td.Start();
        }   
        private void button2_Click(object sender, EventArgs e)
        {
            ThreadWithData twd = new ThreadWithData(2, 200,this.label2, new ExampleCallback(CurrentNumber));
            Thread td = new Thread(new ThreadStart(twd.RunMethod));
            td.Start();
        }
    }
    public class ThreadWithData
    {
        private int start = 0;
        private int end = 0;
        private ExampleCallback callBack;
        private Label lb;

        public ThreadWithData(int start,int end,Label lb,ExampleCallback callBack)
        {
            this.start = start;
            this.end = end;
            this.callBack=callBack;
            this.lb = lb;
        }
        public void RunMethod()
        {
            for(int i=start;i<end;i++)
            {
                Thread.Sleep(1000);
                if (callBack != null)
                    callBack(i,lb);
            }
         
        }
    }
}
2、
3. Back to top
 
4. Top
 
5. Top
 
 
6. Back to top
 
warn Author: ylbtech
Source: http://ylbtech.cnblogs.com/
This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise reserves the right to pursue legal responsibilities.

Guess you like

Origin www.cnblogs.com/storebook/p/12151465.html