C # Async await

Source: Internet
Author: User

This blog to talk about my understanding of the async and Awaite keywords in C #. Let's start by talking about the confusion in my understanding of this asynchronous programming mechanism.
I've seen this article with Async and Await asynchronous Programming (C # and Visual Basic), feeling so easy, asynchronous method to return a Task<tresult> object, with my "deep understanding" of the task class, I conclude that when a synchronization method is invoked, the synchronization method returns a task,.net automatically let the task start running in a background thread, and then the synchronization method returns directly, and when the call to await, the task's wait () method is called. Blocks the current thread from waiting for the task to return results. Then, with my understanding, I wrote the following code

Class program
{
    static void Main ()
    {
        myasyncmethod ();
        Console.readkey ();
    }

    static async void Myasyncmethod ()
    {
        Console.WriteLine ("Call Myasyncmethod ...");
        task<int> Calculateresult = Calculateasync ();
        Console.WriteLine ("Myasyncmethod was called ...");
        int result = await calculateresult;
        Console.WriteLine ($ ' result ' {result} ');
    }

    Static async task<int> Calculateasync ()
    {
        int count = 5;
        for (int i = 0; i < 5; i++)
        {
            thread.sleep (5000);
            Console.WriteLine ($ "Calculating Step {i + 1}");
        }
        Random Random = new Random ();
        return random. Next ();
    }

}

As I understand above, lines 11th and 13th are continuously exported, but the actual output does

Call Myasyncmethod
... Calculating Step 1
Calculating step 2
Calculating step 3
Calculating step 4
Calculating Step 5
Myasyncmethod was called
..... Result is 900866582

That is, the 13th line of code is not executed until Calculateasync () returns. It's not a good deal. Using Async is asynchronous programming. This is clearly a step-by-step implementation. Microsoft Big Liar.
Look at the documentation again:

Asynchronous methods are intended to be non blocking operations. The await expression in an asynchronous method does not block the current thread while the waiting task is running. Instead, the expression registers the remainder of the method as it continues and returns the control to the caller of the asynchronous method.
Async and await keywords do not cause additional threads to be created. Because the asynchronous method does not run on its own thread, it does not require multiple threads. The method will run in the current synchronization context and use the time on the thread only if the method is active. You can use Task.run to move CPU-intensive work to a background thread, but a background thread does not help a process that is waiting for results to become available.
For asynchronous programming, the asynchronous approach is superior to the existing methods in almost every use case. Specifically, this method is more applicable to IO-bound operations than BackgroundWorker because this code is simpler and eliminates the need to prevent contention conditions. When used in conjunction with Task.run, asynchronous programming is more applicable to CPU-bound operations than BackgroundWorker, because asynchronous programming distinguishes the coordination details of the running code from the work that task.run transmits to the thread pool.

As if to see what was understood. Async and await do not create other threads, and asynchronous methods require time-consuming work to be performed in the Task.run. All right, change the code.

Class Program {static void Main () {Myasyncmethod ();
            string input = "";
            while (input = Console.ReadLine ())!= "Q") {Console.WriteLine ($ "Your The input is {input}"); }} static async void Myasyncmethod () {Console.WriteLine ("Call Myasyncmeth
            Od ... ");
            task<int> Calculateresult = Calculateasync ();
            Console.WriteLine ("Myasyncmethod was called ...");
            int result = await calculateresult;
        Console.WriteLine ($ "result was {result}"); Static async task<int> Calculateasync () {Console.WriteLine ("Calculation begin ...")
            ;
            int t = await task.run (() => Calculate ());
            Console.WriteLine ("Calculation complete ...");
        return t;
    The static int Calculate () {//Compute total count of digits in strings.        int count = 5;
                for (int i = 0; i < 5; i++) {thread.sleep (5000);
            Console.WriteLine ($ "Calculating Step {i + 1}");
            } Random Random = new Random (); return random.
        Next (); }

    }

The result of this code is:

Call Myasyncmethod
... Calculation begin ...
.. Myasyncmethod was called
..... Calculating Step 1
Calculating step 2
Calculating step 3
Calculating step 4
Calculating Step 5
Calculation Complete
... Result is 1534528428

The calculation of the process can also be the corresponding user input, such as:

Call Myasyncmethod
... Calculation begin ...
.. Myasyncmethod was called
..... Calculating Step 1
Hello
your input are Hello
calculating step 2
work
your input is off duty
Calculating Step 3
Calculating step 4
World
Your input are world
calculating step 5
Calculation
complete ..... Result is 1805505488

The code above should actually look up from the bottom up. First calculate () is a time-consuming task, calculateasync () is an asynchronous method, and of course, the use of Task.run (). Myasyncmethod () method to invoke the Calculateasync () method. In the main method, calling Myasyncmethod () returns directly, not blocking the current thread, because the current thread also needs to accept the user's input.

Finally, I interpret async and await as a mechanism for easier asynchronous programming, which does not create threads itself, but is asynchronous and simple. However, there must be multiple threads asynchronous, a thread can not run at the same time two methods, but we later in the writing class, we can implement some asynchronous methods by Task.run (), defined as async, which simplifies the programming of the UI thread.

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.