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

前端 未结 21 1643
你的背包
你的背包 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:38

    Here is a quick console program to make it clear to those who follow. The TaskToDo method is your long running method that you want to make async. Making it run async is done by the TestAsync method. The test loops method just runs through the TaskToDo tasks and runs them async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace TestingAsync
    {
        class Program
        {
            static void Main(string[] args)
            {
                TestLoops();
                Console.Read();
            }
    
            private static async void TestLoops()
            {
                for (int i = 0; i < 100; i++)
                {
                    await TestAsync(i);
                }
            }
    
            private static Task TestAsync(int i)
            {
                return Task.Run(() => TaskToDo(i));
            }
    
            private async static void TaskToDo(int i)
            {
                await Task.Delay(10);
                Console.WriteLine(i);
            }
        }
    }
    

提交回复
热议问题