Run the following code:
Static voidMain (string[] args) {Task T=tasktest ();}Private Static AsyncTask tasktest () {awaitDoWork (); Console.WriteLine ("tasktest");}Private Static AsyncTask DoWork () {Console.WriteLine ("Hello world!"); for(inti =0; I <3; i++) { awaitTask.delay ( +); Console.WriteLine ("working ... {0}", i); }}
The results of the operation are as follows:
Conclusion:
1. Async methods are marked async
2. The method marked async must use the await keyword, with the emphasis on await
When the method runs with an await keyword, the compiler opens a separate thread that will run the code that follows it into the thread.
3. Code Execution analysis
Static voidMain (string[] args) { //Program EntryTask t = tasktest ();//Enter Tasktest ()}Private Static AsyncTask tasktest () { await DoWork ();//encounter await, execute DoWork (), open a new thread after execution of Console.WriteLine ("Tasktest"); code Console.WriteLine ("tasktest" );}Private Static AsyncTask DoWork () {Console.WriteLine ("Hello world!");//output "Hello wrold!" in console for(inti =0; I <3; i++) { await task.delay (+);//encounter await, execute Task.delay (1000), open a new thread after executing the code Console.WriteLine ("working ... {0} " , i); }}
Based on the above code execution analysis, the console will eventually print only "Hello world!".
C # Asynchronous Learning One