C # Synchronous and asynchronous calls

Source: Internet
Author: User

This article is only for the purpose of summing up, referring to a lot of predecessors articles, plus a little bit of their own understanding

C # Synchronous and asynchronous threads rely on delegates to accomplish the main need to use the Invoke method of the delegate, BeginInvoke and EndInvoke methods

The so-called synchronization line is to block the current thread to complete the call method, and then continue to call the current thread after the operation, in fact, are executed in the same thread, inefficient. Need to use the Invoke method

The asynchronous thread does not block the current thread, but instead joins the method that needs to be called into the thread pool to perform synchronously, that is, the two and more threads at the same time are executing together and are highly efficient. Need to use BeginInvoke and EndInvoke methods

For details, see the following source code and comments (PS: Most of the summaries are in the comments)

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Runtime.Remoting.Messaging;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceasyncre{classProgram {Static voidMain (string[] args) {Importantfun it=NewImportantfun (); //A synchronous call is shown in turn to invoke a full asynchronous call without a full asynchronous callit.            Sync (); It.            Terribleasync (); It.        Async (); }    }     //define a delegate type     Public Delegate intAddHandler (intXinty); /// <summary>    ///demonstrates synchronous calls and asynchronous calls/// </summary>    classImportantfun {//the method being called        Private intADD (intXinty) {//used to display the thread on which the current method residesConsole.WriteLine ("ADD is running on thread"+Thread.CurrentThread.ManagedThreadId); //thread stuck 6sThread.Sleep (6000); returnX +y; }               /// <summary>        ///synchronous call to add/// </summary>        Public voidSync () {Console.WriteLine ("********* Demo Synchronous call ********"); //print the thread on which the current method residesConsole.WriteLine ("Sync is running on thread"+Thread.CurrentThread.ManagedThreadId); AddHandler Handler=NewAddHandler (ADD); //invoke for synchronous invocation            intResult = handler. Invoke (1,2); Console.WriteLine ("Add is Compete"); Console.WriteLine ("result="+Result);        Console.readkey (); }        /// <summary>        ///Incomplete asynchronous invocation, see note below/// </summary>         Public voidTerribleasync () {Console.WriteLine ("*********** demonstrates an incomplete asynchronous call **********"); Console.WriteLine ("Terribaleasync is running on thread"+Thread.CurrentThread.ManagedThreadId); AddHandler Handler=NewAddHandler (ADD); //asynchronous invocation is typically done together with the Beginvoke and EndInvoke of the delegate//BeginInvoke indicates that an asynchronous call begins to return an interface that represents the calling state (IAsyncResult)IAsyncResult IAR = handler. BeginInvoke (1,2,NULL,NULL); //The above should have 4 parameters, for the moment 3, 4th parameter is set to nullConsole.WriteLine ("Terribaleasync is running on thread"+Thread.CurrentThread.ManagedThreadId); Console.WriteLine (IAR.            ToString ()); //EndInvoke represents the method at the time of the asynchronous call, and the parameter is IAsyncResult type            intresult =handler.            EndInvoke (IAR);            Console.WriteLine (result); Console.WriteLine ("This method of asynchronous invocation is flawed, and the method behind EndInvoke can only guarantee that the middle of begin and end is asynchronous");            Console.readkey (); //This method of asynchronous invocation is flawed, and the method behind EndInvoke can only guarantee that the middle of begin and end is asynchronous//The solution is to use the number 3rd and 4th in BeginInvoke to list the EndInvoke in the callback function .//In fact, to prevent EndInvoke from appearing elsewhere, use the Beginginvoke method to invoke it at once. See the following method        }        /// <summary>        ///the principle of full asynchronous invocation is to call end in BeginInvoke/// </summary>         Public voidAsync () {Console.WriteLine ("*********** Demo Asynchronous call **********"); Console.WriteLine ("Async is running on thread"+Thread.CurrentThread.ManagedThreadId); AddHandler Handler=NewAddHandler (ADD); //new AsyncCallback (Callback) callback function, runtime automatically calls the function when the asynchronous call ends//"Async parameter is Me" can be obtained by Async.asyncstate as a callback parameterHandler. BeginInvoke (1,2,NewAsyncCallback (CallBack),"Async parameter is me"); //above a delegate, callback function callback parameterConsole.WriteLine ("Async is running on thread"+Thread.CurrentThread.ManagedThreadId); //The output of this step can be used to verify whether it is fully asynchronous. Console.readkey (); }        /// <summary>        ///callback function/// </summary>        /// <param name= "IAR" ></param>        Private voidCallBack (IAsyncResult iar) {Console.WriteLine ("CallBack is running on thread"+Thread.CurrentThread.ManagedThreadId); //The former is the result of an asynchronous operation, which represents all theAsyncResult Ar =(AsyncResult) IAR; //get the original delegate object attention to the castAddHandler handler =(AddHandler) ar.asyncdelegate; //End delegate call to get results            intresult =handler.            EndInvoke (AR); //output The 4th parameter in the begin aboveConsole.WriteLine ("The Async calling parameter is"+ar.asyncstate); //Output ResultsConsole.WriteLine ("Result ="+result); }    }   }

As you can see from the picture, synchronous calls are all in one thread

asynchronous invocation occurs in other threads, paying special attention to understanding the callback function

All operations need to use the Invoke method, Begininvoke,endinvoke, a deep understanding of the meaning and parameters of three functions can understand synchronous and asynchronous calls

Hope to be useful to everyone.

C # Synchronous and asynchronous calls

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.