Async and await analysis and asyncawait Analysis
To understand the usage of async and await, first of all, we need to understand the knowledge of tasks, which is not described here, because this is not the focus of this article.
If you are familiar with tasks, you can use async and await to summarize the following three points:
The third point is a bit difficult, so let's talk about it with the code below:
static void Main(string[] args) { Test(); Console.WriteLine("Test End!"); Console.ReadLine(); } static async void Test() { await Test1(); Console.WriteLine("Test1 End!"); } static Task Test1() { Thread.Sleep(1000); Console.WriteLine("create task in test1"); return Task.Run(() => { Thread.Sleep(3000); Console.WriteLine("Test1"); }); }
Execution result:
The result is as follows:
The Main method calls the Test method with the async identifier. the Test method calls the Test1 method through await. When the execution is sequential to Test1, asynchronous operations are encountered; the Test method waits for the asynchronous operation in Test1 to be executed and then executes it. However, the Main method does not have to wait for the Test method to be executed and can continue to be executed.
In the above case, You can implement it without Using async or await. The Code is as follows:
static void Main(string[] args) { Test(); Console.WriteLine("Test End!"); Console.ReadLine(); } static void Test() { var test1=Test1(); Task.Run(() => { test1.Wait(); Console.WriteLine("Test1 End!"); }); } static Task Test1() { Thread.Sleep(1000); Console.WriteLine("create task in test1"); return Task.Run(() => { Thread.Sleep(3000); Console.WriteLine("Test1"); }); }
Finally, this is my personal understanding and summary. You are welcome to discuss it or give me some advice.