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

前端 未结 21 1795
你的背包
你的背包 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条回答
  •  -上瘾入骨i
    2020-11-21 05:36

    Showing the above explanations in action in a simple console program:

    class Program
    {
        static void Main(string[] args)
        {
            TestAsyncAwaitMethods();
            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    
        public async static void TestAsyncAwaitMethods()
        {
            await LongRunningMethod();
        }
    
        public static async Task LongRunningMethod()
        {
            Console.WriteLine("Starting Long Running method...");
            await Task.Delay(5000);
            Console.WriteLine("End Long Running method...");
            return 1;
        }
    }
    

    And the output is:

    Starting Long Running method...
    Press any key to exit...
    End Long Running method...
    

    Thus,

    1. Main starts the long running method via TestAsyncAwaitMethods. That immediately returns without halting the current thread and we immediately see 'Press any key to exit' message
    2. All this while, the LongRunningMethod is running in the background. Once its completed, another thread from Threadpool picks up this context and displays the final message

    Thus, not thread is blocked.

提交回复
热议问题