George Mauer
George Mauer

Reputation: 122172

Can the await keyword result in parallel code?

Suppose I have two async functions

Result1 result1 = await getResult1();
Result2 result2 = await getResult2();
doSomething(result1, result2);

Ideally I would hope that the compiler analyzes my method sees that getResult2() does not depend on the results of getResult1() and compiles this to code that schedules both to run simultaneously, awaiting the results of both before continuing.

Question 1: Is that what happens?

Question 2: If not, how do I make that happen assuming that Result1 and Result2 share no base type and I therefore cannot use Task.WhenAll()

Upvotes: 3

Views: 118

Answers (2)

Daniel
Daniel

Reputation: 16464

  1. No, in your code you are waiting for the first result before starting the second operation.

  2. First start both tasks, then await them:

    Task<Result1> task1 = getResult1();
    Task<Result2> task2 = getResult2();
    doSomething(await task1, await task2);
    

Upvotes: 4

Servy
Servy

Reputation: 203827

Is that what happens?

No. await simply means, more or less, "don't continue executing code until the following task has completed".

how do I make that happen

Start both tasks first, then await until they are both done:

var firstTask = getResult1();
var secondTask = getResult2();
await Task.WhenAll(firstTask, secondTask);
doSomething(firstTask.Result, secondTask.Result);

Upvotes: 7

Related Questions