How and when to use ‘async’ and ‘await’

前端 未结 21 1747
你的背包
你的背包 2020-11-21 05:07

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perfo

21条回答
  •  遥遥无期
    2020-11-21 05:33

    See this fiddle https://dotnetfiddle.net/VhZdLU (and improve it if possible) for running a simple console application which shows usages of Task, Task.WaitAll(), async and await operators in the same program.

    This fiddle should clear your execution cycle concept.

    Here is the sample code

    using System;
    using System.Threading.Tasks;
    
    public class Program
    {
        public static void Main()
        {               
            var a = MyMethodAsync(); //Task started for Execution and immediately goes to Line 19 of the code. Cursor will come back as soon as await operator is met       
            Console.WriteLine("Cursor Moved to Next Line Without Waiting for MyMethodAsync() completion");
            Console.WriteLine("Now Waiting for Task to be Finished");       
            Task.WaitAll(a); //Now Waiting      
            Console.WriteLine("Exiting CommandLine");       
        }
    
        public static async Task MyMethodAsync()
        {
            Task longRunningTask = LongRunningOperation();
            // independent work which doesn't need the result of LongRunningOperationAsync can be done here
            Console.WriteLine("Independent Works of now executes in MyMethodAsync()");
            //and now we call await on the task 
            int result = await longRunningTask;
            //use the result 
            Console.WriteLine("Result of LongRunningOperation() is " + result);
        }
    
        public static async Task LongRunningOperation() // assume we return an int from this long running operation 
        {
            Console.WriteLine("LongRunningOperation() Started");
            await Task.Delay(2000); // 2 second delay
            Console.WriteLine("LongRunningOperation() Finished after 2 Seconds");
            return 1;
        }   
    
    }
    

    Trace coming from Output Window:

提交回复
热议问题