1

What would code look like for a single method that has 2 anonymous functions inside, which are both tasks that use Task.WhenAll so that they run in parallel but wait for both to finish before the method continues and returns?

pseudo code:

MethodX
{ 
  Task () => {do work}
  Task () => {do work}
  Task.WhenAll()
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
StackMan
  • 55
  • 7
  • It's literally [WhenAll](https://msdn.microsoft.com/en-us/library/hh194874(v=vs.110).aspx), not sure I understand the question. – Ashley Medway Feb 06 '18 at 15:45
  • Didn't you just answer your own question? With `WhenAll(t1, t2)` ? – H H Feb 06 '18 at 15:46
  • Looking for a C# example in the same form as pseudo code. Just thought I would see how others would present it. – StackMan Feb 06 '18 at 15:49

1 Answers1

0

I like:

async Task MethodX() {
    Task x = ...
    Task y = ...

    await x;
    await y;
}

Although I'd probably add a sync hot-path:

Task MethodX() {
    async Task Awaited(Task a, Task b) {
        await a;
        await b;
    }
    Task x = ...;
    Task y = ...;

    if (x.Status == TaskStatus.RanToCompletion &
        y.Status == TaskStatus.RanToCompletion)
        return Task.CompletedTask; // sync

    return Awaited(x, y); // async
}

but this would work too:

Task MethodX() {
    Task x = ...
    Task y = ...

    return Task.WhenAll(x, y);
}

Another approach is Parallel:

Parallel.Invoke(thingA, thingB);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • well the await, await means task x has to finish before task y starts right? – Ashley Medway Feb 06 '18 at 15:47
  • 1
    @AshleyMedway nope! if they're actually async, then they should be concurrent here; but it depends a lot on the concurrency model of the two tasks – Marc Gravell Feb 06 '18 at 15:49
  • 1
    @AshleyMedway If you start task y after awaiting x, then yes, you don't start it until after the await. If you start it before awaiting x, then you have started it before task x finishes. This code does the latter, not the former. You could write either though. – Servy Feb 06 '18 at 15:53
  • Thanks @Servy, that's is what I thought but wasn't sure when I saw the answer – Ashley Medway Feb 06 '18 at 15:54
  • Would methodX need to be marked task "Task MethodX" or could it also just be marked "async"as in my original pseudo code. the main objective is that both task run concurrent but the method doesn't continue until both tasks are finished – StackMan Feb 06 '18 at 16:12
  • @StackMan that should work fine either way, *as long as** those tasks actually are async. If they complete synchronously: this entire code path is already synchronous, so if they are actually synchronous jobs pretending to be async: you'll need to use `Parallel` or similar – Marc Gravell Feb 06 '18 at 16:27