Running multiple async tasks and waiting for them all to complete

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

    You can use WhenAll which will return an awaitable Task or WaitAll which has no return type and will block further code execution simular to Thread.Sleep until all tasks are completed, canceled or faulted.

    Example

    var tasks = new Task[] {
        TaskOperationOne(),
        TaskOperationTwo()
    };
    
    Task.WaitAll(tasks);
    // or
    await Task.WhenAll(tasks);
    

    If you want to run the tasks in a praticular order you can get inspiration form this anwser.

    0 讨论(0)
  • 2020-11-22 14:35

    The best option I've seen is the following extension method:

    public static Task ForEachAsync<T>(this IEnumerable<T> sequence, Func<T, Task> action) {
        return Task.WhenAll(sequence.Select(action));
    }
    

    Call it like this:

    await sequence.ForEachAsync(item => item.SomethingAsync(blah));
    

    Or with an async lambda:

    await sequence.ForEachAsync(async item => {
        var more = await GetMoreAsync(item);
        await more.FrobbleAsync();
    });
    
    0 讨论(0)
  • 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<Cat>();
    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
    }
    
    0 讨论(0)
提交回复
热议问题