C # syntax--await and Async's correct opening method

Source: Internet
Author: User

c#5.0 has introduced new syntax, await and async, but it is believed that people still seldom use them. There are many articles about await and async, but there is no such a feeling that after you have finished, you always feel that this thing is very good, but when used, always can't remember, or do not know how to use.

Why is it? I think everyone's await and async's open way is not correct.

The right way to open is to first look at the use of constraints.

1. Await can only be used within the function marked with async.

2. The await wait function must mark Async.

Does it feel like it's a loop? Yes, that's a loop. That's why people don't use them very much. This loop is annoying, so how do you break the cycle?

"Quite simply, await waits for a thread, not a function." 】

Don't you understand? It's okay, keep looking.

Let's start from the beginning and look at a set of comparisons.

public static int noasynctest () {   return 1;} public static async task<int> Asynctest () {return 1;}

Async task<int> equals int

This means that when we call these two functions normally, they are equivalent. So what is the purpose of modifying an int with an async task<int>?

The goal is to let this method be called await asynctest (), but this call does not open the thread, so the laborious modification is not meaningless.

Of course not, when would it make sense to await asynctest ()?

We then look down and modify the Asynctest as follows. Then, when you call await Asynctest (), you will magically discover that there are still no eggs ...

The Excute method executes properly, while the thread running within Asynctest executes its own.

public static async void Excute () {       Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Start Excute" + datetime.no W);       await Asynctest ();       Console.WriteLine (Thread.CurrentThread.GetHashCode () + "End Excute" + DateTime.Now);} public static async task<int> Asynctest () {        Task.run (() =            {                Console.WriteLine ( Thread.CurrentThread.GetHashCode () + "Run1" + datetime.now);                Thread.Sleep (+);            });            return 1; }

Don't worry, we'll make a slight adjustment, and we'll add more after the thread. Getawaiter (). GetResult (). What is the use of this sentence? is used to get the return value of the thread.

The logic is that if you want to get the thread to return the result, it's natural to wait for the thread to end.

Run it and we'll look at the results below.

public static async task<int> asynctest ()        {            Task.run (() =            {                Console.WriteLine ( Thread.CurrentThread.GetHashCode () + "Run1" + datetime.now);                Thread.Sleep (+);            }) . Getawaiter (). GetResult ();            return 1;        }

 

But it seems to await asynctest (); Yes, the truth is, he really doesn't work ...

So how do we make him work?

First, we define a normal function whose return value is a task, then we get the task, run it, and wait for the task with await.

So we get the result.

public static async void Excute ()        {            Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Start Excute" + Dateti Me. Now);            var waittask = Asynctestrun ();            Waittask.start ();            int i = await waittask;            Console.WriteLine (Thread.CurrentThread.GetHashCode () + "I" + i);            Console.WriteLine (Thread.CurrentThread.GetHashCode () + "End Excute" + DateTime.Now);        }        public static task<int> Asynctestrun ()        {            task<int> t = new task<int> (() = {                Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Run1" + datetime.now);                Thread.Sleep (+);                return;            });            return t;        }

  

, so write await asynctest (); it works.

So, in that sentence, await is a thread, not a function.

But in the picture, we find it strange that the end of Excute is also thread 3, not thread 1. In other words, await will optimize the thread.

Let's look at the comparison of the two sets of code below, so that we can understand the next await more clearly.

First set, use await to wait for thread.

public static async void Excute () {   Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Start Excute" + datetime.no W);   await singleawait ();    Console.WriteLine (Thread.CurrentThread.GetHashCode () + "End Excute" + DateTime.Now);}      public static async Task singleawait () {     Console.WriteLine (Thread.CurrentThread.GetHashCode () + "awaittest start" + DateTime.Now);     Await Task.run (() =            {                Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Run1" + datetime.now);                Thread.Sleep (+);            });            Await Task.run (() =            {                Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Run2" + DateTime.Now); C13/>thread.sleep (+);            });            Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Awaittest End" + datetime.now);            return;}

The second group, which waits for threads using the wait thread result.

 public static async void Excute () {Console.WriteLine (            Thread.CurrentThread.GetHashCode () + "Start Excute" + DateTime.Now);      await singlenoawait ();        Console.WriteLine (Thread.CurrentThread.GetHashCode () + "End Excute" + DateTime.Now);  }public static async Task singlenoawait () {Console.WriteLine (Thread.CurrentThread.GetHashCode () + "singlenoawait start"       + DateTime.Now);                 Task.run (() = {Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Run1" + DateTime.Now);            Thread.Sleep (1000); }). Getawaiter ().            GetResult (); Task.run (() = {Console.WriteLine (Thread.CurrentThread.GetHashCode () + "Run2" + DATETIME.N                OW);            Thread.Sleep (1000); }). Getawaiter ().            GetResult ();            Console.WriteLine (Thread.CurrentThread.GetHashCode () + "singlenoawait End" + DateTime.Now); return;} 

Can be clearly seen, the second group, the thread back to the main thread 1, and the first group, has been optimized to thread 4.

Conclusion

Await is a handy syntax, he does make the code simple, but he actively optimizes the functionality of the thread, and if you don't know it, it can cause some strange bugs to happen.

This is also why the authorities only provide an example of the await invocation service, because, in the program calls, await or to understand, then use, before it is safe.

C # syntax--await and Async's correct opening method

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.