C #--Async and Await FAQ

Source: Internet
Author: User
Tags modifier
1. Explanations on official Async documents

About C #

I think the following is a good understanding of await in the documentation, ^^

Use the async modifier to specify a method, lambda expression, or anonymous method as asynchronous. If this modifier is used in a method or an expression, it is called an asynchronous method

Public async task<int> Examplemethodasync ()  
{  
    //.....  

An async method uses the await keyword TODO pentially long-running work without blocking the caller ' s thread

long-running work without blocking the caller's thread

The Async Modify method will run synchronously until its first await expression is reached, and the method is suspended until the waiting task completes. Also, as shown in the following section example, the control is returned to the caller of the method

If the Async keyword modifies a method that does not contain an await expression or statement, the method executes synchronously. The compiler warning notifies you of any asynchronous methods that do not contain await, because the situation may indicate an error

The Async keyword is a contextual keyword because it is a keyword only if it modifies a method, a lambda expression, or an anonymous method . In all other contexts, it is interpreted as an identifier 1.1 Example (want to run to see the topmost link)

The following example shows the structure and flow of control between

An Async event handler

Startbutton_click

Async method

Examplemethodasync

Private async void Startbutton_click (object sender, RoutedEventArgs e) {//Examplemethodasync returns a TASK&LT;INT&G 
    t;, which means that this method eventually produces a int result.  
    However, Examplemethodasync returns the Task<int> value as soon as it reaches an await.
    Resultstextbox.text + = "\ n";
        try {int length = await examplemethodasync (); Note this you could put "await Examplemethodasync ()" In the next line where//"Length" are, but due to when ' + = ' Fetches the value of Resultstextbox, you//would not to the global side effect of Examplemethodasync Setti  
        ng the text.
    Resultstextbox.text + = String.Format ("Length: {0}\n", length);  
    The catch (Exception) {//Process the Exception if one occurs.
    } public Async task<int> Examplemethodasync () {var httpclient = new HttpClient (); int exampleint = (await Httpclient.getstringasync ("http://msdn.microsoft.com")). Length;
    Resultstextbox.text + = "Preparing to finish examplemethodasync.\n"; After the "following return" statement, any method of that ' s awaiting//Examplemethodasync (in this case, Startbutton  
    _click) can get the//integer result.
return exampleint;  
//Output://Preparing to finish Examplemethodasync.   length:53292
1.2. Return type

The return type of an asynchronous method can be a task, task, or void. A method cannot declare any ref or out parameter, but a method with such a parameter can be invoked.

If the return statement of an asynchronous method specifies an operand of the TResult type, you should specify the Task as the return type of the method. If a meaningful value is not returned when the method completes, the Task should be used. That is, a call to a method returns a task, but when the task completes, any await expression that waits for the task evaluates to void.

You should primarily use the void return type to define event handlers that require this return type. VOID returns the caller of the asynchronous method cannot wait, and cannot catch exception 2 thrown by the method . Await

The await operator is applied to the task in the asynchronous method to suspend the execution method until the task waiting is completed. Suspend is explained below, the task indicates the work in progress

Asynchronous methods that use await must be decorated with the Async keyword . A method that is defined with the Async modifier and typically contains one or more await expressions is called an asynchronous method

The task of applying the await operator is usually the return value of a method call that implements a task-based asynchronous Pattern. Examples include value 2.1 await return types for task or task types

If await is applied to the result of a method call that returns task<tresult> , the type of the await expression is TResult. If await is applied to the result of a method call that returns a Task, the type of the await expression is void. The following example demonstrates the difference

Keyword await used with a is returns a task<tresult>.  
TResult result = await asyncmethodthatreturnstasktresult ();  

Keyword await used with a to that returns a Task.  
await Asyncmethodthatreturnstask ();  

The await expression does not block the thread that is executing it (simply understood as the main thread). Instead, the compiler registers the remaining asynchronous methods as a continuation of the task waiting. control is then returned to the caller of the asynchronous method . When the task completes (who performs the task). Who is hanging up. The main thread, the main thread that finishes the task (at which time the asynchronous task does not end, so it is to scrape the wait result), it invokes its continuation task, and the execution of the asynchronous method resumes at the paused position.

A await expression can be present only in the immediate enclosing body of a method labeled by the Async modifier (the bodies of immediately enclosing method), lambda expressions, or asynchronous methods. The term "await" is used only as a keyword in this context. In other locations, it is interpreted as an identifier. In a method, lambda expression, or anonymous method, a await expression cannot occur in a synchronization function body, a query expression, a lock statement block, or an unsafe context

About the document on the await I've been confused for a long time.

An await expression does the ' thread ' which it is executing. Instead, it causes the compiler to sign up the rest of the ' async method as a continuation on the awaited task

The await expression does not block the thread that is executing it ( simply understood as the main thread). Instead, the compiler registers the remaining asynchronous method ( the asynchronous thread that is still executing after the main thread ends ) as a continuation of the task waiting. Control is then returned to the caller of the asynchronous method. When the task completes, it invokes its continuation task, and the execution of the asynchronous method is restored at the paused location at 3. Official illustration

4. Put the code over here.

Class program
    {
        async task<int> Accessthewebasync ()
        {
            httpclient client = new HttpClient ();

            Task<string> getstringtask = client. Getstringasync ("http://msdn.microsoft.com");

            Doindependentwork ();

            String urlcontents = await getstringtask;

            Console.WriteLine ("---------------" +urlcontents.length);
            return urlcontents.length;
        }

        void Doindependentwork ()
        {
            Console.WriteLine ("----------");
        }
        static void Main (string[] args)
        {program
            PR = new program ();
            task<int> my = pr. Accessthewebasync ();
            Console.WriteLine (My. result);
            Console.ReadLine ();
        }
    

Can run, is lazy

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.