await an enumerable of tasks in csharp

To await an enumerable of tasks, you can use the Task.WhenAll method. This method takes an IEnumerable of Task objects and returns a Task that represents the completion of all the input tasks.

Here's an example of how to use Task.WhenAll to await an enumerable of tasks:

main.cs
async Task WaitForTasks(IEnumerable<Task> tasks)
{
    await Task.WhenAll(tasks);
    Console.WriteLine("All tasks have completed.");
}
136 chars
6 lines

In this example, the WaitForTasks method takes an IEnumerable of Task objects as input. It then calls Task.WhenAll to await the completion of all the tasks in the input enumerable. Once all the tasks have completed, the method writes a message to the console.

You can call this method with an enumerable of tasks like this:

main.cs
var tasks = new List<Task>
{
    DoSomeWorkAsync(),
    DoOtherWorkAsync(),
    DoMoreWorkAsync()
};

await WaitForTasks(tasks);
129 chars
9 lines

In this example, we create a List of Task objects and pass it to WaitForTasks to await the completion of all the tasks.

related categories

gistlibby LogSnag