A detailed explanation of the use of async and await in C #

Source: Internet
Author: User
This article mainly describes the C # of Async and await the specific use of small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

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

Look at an example:


public class MyClass {public   MyClass ()   {     displayvalue ();//not blocked     here System.Diagnostics.Debug.WriteLine ("MyClass () End.");   Public task<double> Getvalueasync (double num1, double num2)   {     return Task.run (() + =     {for       ( int i = 0; i < 1000000; i++)       {         num1 = num1/num2;       }       return NUM1;     });   Public async void Displayvalue ()   {     Double result = await Getvalueasync (1234.5, 1.01);// A new thread is opened here to process the Getvalueasync task, and then the method returns immediately     //after which all the code will be encapsulated as a delegate and 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.5, 1.01). Getawaiter ();   Awaiter. OnCompleted (() =     {       double result = Awaiter. GetResult ();       System.Diagnostics.Debug.WriteLine ("Value is:" + 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 class Taskasynchelper {//<summary>////To run a method function asynchronously and execute a callback when execution is complete callback//</summary&   Gt <param name= "function" > Async method, the method has no parameters, 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 void RunAsync (action function, action callback) {func<system.threading.tasks.task> Taskfunc = () = {return System.Threading.Tasks.Task.Run ()       = = {function ();     });     };     await Taskfunc ();   if (callback! = NULL) callback (); }///<summary>//To run a method function asynchronously and execute the callback callback//</summary>//<typeparam name= "TResu LT "> Return type of async method </typeparam>//<param name=" function "> Async method, the method has no arguments, the return type must be tresult</param>/// Lt;param name= "Callback" > The callback method executed when the Async method executes, the method parameter is TResult, the return type must be void</param> public static async void Runasync<tresult> (func<tresult> functiOn, Action<tresult> callback) {func<system.threading.tasks.task<tresult>> TaskFunc = () =           {return System.Threading.Tasks.Task.Run () = {return function ();       });     };     TResult RLT = await taskfunc ();   if (callback! = NULL) callback (RLT); } }

The

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

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.