如何在 returns 集合的 lambda 中使用异步

How to use async within a lambda which returns a collection

我有一个异步方法"upstream"。我正在尝试遵循最佳实践并在堆栈中一直使用 qith async。

在 MVC 的控制器操作中,如果我依赖 .Result(),我可以预见会遇到死锁问题。

将控制器操作更改为异步似乎是可行的方法,但问题是异步方法在 lambda 中被多次调用。

我怎样才能等待 returns 多个结果

public async Task<JsonResult>  GetLotsOfStuff()
{
    IEnumerable<ThingDetail> things=  previouslyInitialisedCollection
                                      .Select(async q => await GetDetailAboutTheThing(q.Id)));
    return Json(result, JsonRequestBehavior.AllowGet);

}

你可以看到我已经尝试使 lambda 异步,但这只会给出编译器异常:

无法转换源类型

System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<ThingDetail> to target type System.Collections.Generic.IEnumerable<ThingDetail>

我哪里错了?

  • 将您的 Thing 集合转换为 Task<Thing> 集合。
  • 然后使用 Task.WhenAll 加入所有这些任务并等待它。
  • 等待联合任务将获得Thing[]


public async Task<JsonResult>  GetLotsOfStuff()
{
    IEnumerable<Task<ThingDetail>> tasks = collection.Select(q => GetDetailAboutTheThing(q.Id));

    Task<int[]> jointTask = Task.WhenAll(tasks);

    IEnumerable<ThingDetail> things = await jointTask;

    return Json(things, JsonRequestBehavior.AllowGet);
}

或者,简洁地使用类型推断:

public async Task<JsonResult>  GetLotsOfStuff()
{
    var tasks = collection.Select(q => GetDetailAboutTheThing(q.Id));
    var things = await Task.WhenAll(tasks);

    return Json(things, JsonRequestBehavior.AllowGet);
}

Fiddle: https://dotnetfiddle.net/78ApTI

注意:由于 GetDetailAboutTheThing 似乎 return 一个 Task<Thing>,惯例是在其名称后附加 Async - GetDetailAboutTheThingAsync.