ChatGPT解决这个技术问题 Extra ChatGPT

multiple awaits vs Task.WaitAll - equivalent?

In terms of performance, will these 2 methods run GetAllWidgets() and GetAllFoos() in parallel?

Is there any reason to use one over the other? There seems to be a lot happening behind the scenes with the compiler so I don't find it clear.

============= MethodA: Using multiple awaits ======================

public async Task<IHttpActionResult> MethodA()
{
    var customer = new Customer();

    customer.Widgets = await _widgetService.GetAllWidgets();
    customer.Foos = await _fooService.GetAllFoos();

    return Ok(customer);
}

=============== MethodB: Using Task.WaitAll =====================

public async Task<IHttpActionResult> MethodB()
{
    var customer = new Customer();

    var getAllWidgetsTask = _widgetService.GetAllWidgets();
    var getAllFoosTask = _fooService.GetAllFos();

    Task.WaitAll(new List[] {getAllWidgetsTask, getAllFoosTask});

    customer.Widgets = getAllWidgetsTask.Result;
    customer.Foos = getAllFoosTask.Result;

    return Ok(customer);
}

=====================================

In your first example the two methods will be called sequentially and in the second they'll be run in parallel, so they aren't equivalent. Also, in your second method you are blocking while executing the tasks.
MethodA will execute _fooService.GetAllFoos() only when _widgetService.GetAllWidgets() has finished, methodB will execute it when the uncompleted Task from _fooService.GetAllFoos() returns.
@DanielKelley The second does not guarantee that they'll be run in parallel. As is so often emphasized in other answers and explanations of asynchronous operations, they are not necessarily multi-threaded or parallel. Some even insist that they are not multi-threaded at all, but that is an unnecessary limitation. Depending on the implementation, they might be run in parallel, but about the strongest that can be said is that they are not guaranteed to run sequentially.

i
i3arnon

The first option will not execute the two operations concurrently. It will execute the first and await its completion, and only then the second.

The second option will execute both concurrently but will wait for them synchronously (i.e. while blocking a thread).

You shouldn't use both options since the first completes slower than the second and the second blocks a thread without need.

You should wait for both operations asynchronously with Task.WhenAll:

public async Task<IHttpActionResult> MethodB()
{
    var customer = new Customer();

    var getAllWidgetsTask = _widgetService.GetAllWidgets();
    var getAllFoosTask = _fooService.GetAllFos();

    await Task.WhenAll(getAllWidgetsTask, getAllFoosTask);

    customer.Widgets = await getAllWidgetsTask;
    customer.Foos = await getAllFoosTask;

    return Ok(customer);
}

Note that after Task.WhenAll completed both tasks already completed so awaiting them completes immediately.


Thanks. This is what I needed. The ".Result" was bothering me and your answer avoids that.
You can also completely skip await Task.WhenAll(getAllWidgetsTask, getAllFoosTask); and just await tasks (just start second task before awaiting first).
@kwesoly that's true, but it's a little bit more efficient to "suspend" only once.
@i3arnon - sounds as good reason, there is really no point to switch context just to await again.
@StephenHolt There's exactly one difference between the two. Result wraps any exceptions in an AggregateException, which you then need to unwrap in all of your error handling code. await unwraps it for you. Other than that they're identical.
N
Nitram

Short answer: No.

Task.WaitAll is blocking, await returns the task as soon as it is encountered and registers the remaining part of the function and continuation.

The "bulk" waiting method you were looking for is Task.WhenAll that actually creates a new Task that finishes when all tasks that were handed to the function are done.

Like so: await Task.WhenAll({getAllWidgetsTask, getAllFoosTask});

That is for the blocking matter.

Also your first function does not execute both functions parallel. To get this working with await you'd have to write something like this:

var widgetsTask = _widgetService.GetAllWidgets();
var foosTask = _fooService.GetAllWidgets();
customer.Widgets = await widgetsTask;
customer.Foos = await foosTask;

This will make the first example to act very similar to the Task.WhenAll method.


n
nvoigt

Only your second option will run them in parallel. Your first will wait on each call in sequence.


K
Kasper Holdum

As soon as you invoke the async method it will start executing. Whether it will execute on the current thread (and thus run synchronously) or it will run async is not possible to determine.

Thus, in your first example the first method will start doing work, but then you artificially stops the flow of the code with the await. And thus the second method will not be invoked before the first is done executing.

The second example invokes both methods without stopping the flow with an await. Thus they will potentially run in parallel if the methods are asynchronous.


p
pnizzle

As an addition to what @i3arnon said. You will see that when you use await you are forced to have to declare the enclosing method as async, but with waitAll you don't. That should tell you that there is more to it than what the main answer says. Here it is:

WaitAll will block until the given tasks finish, it does not pass control back to the caller while those tasks are running. Also as mentioned, the tasks are run asynchronous to themselves, not to the caller.

Await will not block the caller thread, it will however suspend the execution of the code below it, but while the task is running, control is returned back to the caller. For the fact that control is returned back to the caller (the called method is running async), you have to mark the method as async.

Hopefully the difference is clear. Cheers