Running multiple async tasks and waiting for them all to complete

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

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

    public static Task ForEachAsync(this IEnumerable sequence, Func 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();
    });
    

提交回复
热议问题