5

I think async/await keywords here are redundant.

Parallel.Invoke(
    async () => await DoSomethingAsync(1).ConfigureAwait(false),
    async () => await DoSomethingAsync(2).ConfigureAwait(false)
);

Given a number of task-returning methods, is there any more straightforward way to run them in parallel and return when all are complete?

orad
  • 15,272
  • 23
  • 77
  • 113
  • 4
    Read up on Task.WhenAll – Nkosi Dec 02 '16 at 02:49
  • 5
    `Task.WhenAll(DoSomethingAsync(1), DoSomethingAsync(2))` – Enigmativity Dec 02 '16 at 03:12
  • Why are you mixing `Parallel.Invoke` and `async/await`? Parallel.Invoke will run each call in a separate thread anyway and *block* while waiting for them to finish. Or you can store the individual tasks in an array and await the array – Panagiotis Kanavos Dec 02 '16 at 10:10
  • @PanagiotisKanavos when awaiting array I get: `Task[]' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task[]' could be found` – orad Dec 02 '16 at 18:36
  • @orad as others have already answered, you can await an array of tasks with `await Task.WhenAll(...)` – Panagiotis Kanavos Dec 05 '16 at 08:02

1 Answers1

4
await Task.WhenAll(DoSomethingAsync(1), DoSomethingAsync(2));

Optionally add .ConfigureAwait(false) to the WhenAll(), depending on context.

sellotape
  • 8,034
  • 2
  • 26
  • 30
  • Or `Task.WaitAll` if the outer method isn't currently `async` and/or they don't want to change from the existing semantic of the `Parallel.Invoke` which is blocking, not async. – Damien_The_Unbeliever Dec 02 '16 at 08:00
  • @Damien_The_Unbeliever Yes I guess so, if that's a specific requirement; there isn't really enough context in the question to know. – sellotape Dec 02 '16 at 08:03
  • This works! [This comment here](https://stackoverflow.com/questions/25009437/running-multiple-async-tasks-and-waiting-for-them-all-to-complete#comment65496481_25010220) confused me that "`Task.WhenAll` doesn't start the tasks for you. You have to provide them "hot", meaning already started.", but apparently you don't need to do that. – orad Dec 03 '16 at 00:57
  • `Task.WhenAll()` is not what starts the tasks; rather `DoSomethingAsync()` returns an _already started_ `Task` – sellotape Dec 03 '16 at 07:32