Talk about Async and await in C # (GO)

Source: Internet
Author: User

Source: http://blog.csdn.net/tianmuxia/article/details/17675681

Async and await are introduced in C # 5.0. These two keywords can make it easier for you to write asynchronous code.

 Public classmyclass{ PublicMyClass () {displayvalue ();//There's no blocking .System.Diagnostics.Debug.WriteLine ("MyClass () End."); }     Publictask<Double> Getvalueasync (DoubleNUM1,Doublenum2) {        returnTask.run (() =        {             for(inti =0; I <1000000; i++) {NUM1= NUM1/num2; }            returnNUM1;    }); }     Public Async voidDisplayvalue () {Doubleresult =awaitGetvalueasync (1234.5,1.01);//a new thread is opened here to process the Getvalueasync task, and the method immediately returns//All code after this is encapsulated as a delegate, which is called when the Getvalueasync task completes.System.Diagnostics.Debug.WriteLine ("Value is:"+result); }}

The ASYNC keyword tag is called asynchronously in the MyClass constructor, Displayvalue (), and the Displayvalue () method executes an await keyword-tagged asynchronous task Getvalueasync (), This asynchronous task must be either a task or a task<tresult> as the return value, and we also see that the actual type returned when the asynchronous task execution completes is void or the Tresult,displayvalue () method await All code after Getvalueasync () will be executed when the asynchronous task is completed.

The code that is actually executed by the Displayvalue () method is as follows:

 Public void Displayvalue () {    System.Runtime.CompilerServices.TaskAwaiter<double> Awaiter = Getvalueasync (1234.51.01). Getawaiter ();     + =        {            double result = Awaiter. GetResult ();            System.Diagnostics.Debug.WriteLine ("" + result);        

As you can see, the async and await keywords simply make the above code easier to understand.

The output of the program is as follows:

MyClass () End.

Value is:2.47032822920623e-322

Here is a static Class I wrote that makes it easy to execute an asynchronous invocation of a normal function:

     Public Static classTaskasynchelper {/// <summary>        ///asynchronously runs a method function and executes a callback when execution is complete callback/// </summary>        /// <param name= "function" >Async method, the method has no arguments, the return type must be void</param>        /// <param name= "callback" >The callback method that executes when the Async method executes, without parameters, the return type must be void</param>         Public Static Async voidRunAsync (Action function, action callback) {Func<System.Threading.Tasks.Task> Taskfunc = () =            {                returnSystem.Threading.Tasks.Task.Run (() ={function ();            });            }; awaitTaskfunc (); if(Callback! =NULL) callback (); }        /// <summary>        ///asynchronously runs a method function and executes a callback when execution is complete callback/// </summary>        /// <typeparam name= "TResult" >The return type of an async method</typeparam>        /// <param name= "function" >Async method, the method has no arguments, the return type must be TResult</param>        /// <param name= "callback" >The callback method that executes when the asynchronous method executes, the method parameter is TResult, and the return type must be void</param>         Public Static Async voidRunasync<tresult> (func<tresult> function, action<tresult>callback) {Func<System.Threading.Tasks.Task<TResult>> Taskfunc = () =                {                    returnSystem.Threading.Tasks.Task.Run (() =                        {                            returnfunction ();                });            }; TResult RLT=awaitTaskfunc (); if(Callback! =NULL) callback (RLT); }    }

It is easy to use the method name as a parameter, and the most common thing is to pass the time-consuming serialization function in order to avoid blocking the UI process, causing the lag and affecting the user experience.

Talk about Async and await in C # (GO)

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.