Running multiple async tasks and waiting for them all to complete

后端 未结 9 1491
渐次进展
渐次进展 2020-11-22 13:36

I need to run multiple async tasks in a console application, and wait for them all to complete before further processing.

There\'s many articles out there, but I see

9条回答
  •  情话喂你
    2020-11-22 14:43

    Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

    var cats = new List();
    var dog = new Dog();
    
    var loadDataTasks = new Task[]
    {
        Task.Run(async () => cats = await LoadCatsAsync()),
        Task.Run(async () => dog = await LoadDogAsync())
    };
    
    try
    {
        await Task.WhenAll(loadDataTasks);
    }
    catch (Exception ex)
    {
        // handle exception
    }
    

提交回复
热议问题