Running multiple async tasks and waiting for them all to complete

后端 未结 9 1590
渐次进展
渐次进展 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:27

    There should be a more succinct solution than the accepted answer. It shouldn't take three steps to run multiple tasks simultaneously and get their results.

    1. Create tasks
    2. await Task.WhenAll(tasks)
    3. Get task results (e.g., task1.Result)

    Here's a method that cuts this down to two steps:

        public async Task> WhenAllGeneric(Task task1, Task task2)
        {
            await Task.WhenAll(task1, task2);
            return Tuple.Create(task1.Result, task2.Result);
        }
    

    You can use it like this:

    var taskResults = await Task.WhenAll(DoWorkAsync(), DoMoreWorkAsync());
    var DoWorkResult = taskResults.Result.Item1;
    var DoMoreWorkResult = taskResults.Result.Item2;
    

    This removes the need for the temporary task variables. The problem with using this is that while it works for two tasks, you'd need to update it for three tasks, or any other number of tasks. Also it doesn't work well if one of the tasks doesn't return anything. Really, the .Net library should provide something that can do this

提交回复
热议问题