多个等待 vs Task.WaitAll - 等效吗? [英] multiple awaits vs Task.WaitAll - equivalent?

查看:14
本文介绍了多个等待 vs Task.WaitAll - 等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在性能方面,这两个方法会同时运行 GetAllWidgets()GetAllFoos() 吗?

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.

============ 方法A:使用多个等待======================

============= 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);
}

============== 方法B:使用Task.WaitAll ======================

=============== 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);
}

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

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

推荐答案

第一个选项不会同时执行两个操作.它将执行第一个并等待其完成,然后才执行第二个.

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.

您应该使用 Task.WhenAll 异步等待这两个操作:

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);
}

请注意,在 Task.WhenAll 完成后,两个任务都已经完成,因此等待它们立即完成.

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

这篇关于多个等待 vs Task.WaitAll - 等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆