我有一个异步“上游”方法。我正在尝试遵循最佳实践并在堆栈中一直采用 qith async。
在 MVC 的 Controller 操作中,如果我依赖 .Result(),我可以预见会遇到死锁问题。
将 Controller 操作更改为异步似乎是可行的方法,但问题是异步方法在 lambda 中被多次调用。
我如何等待返回多个结果的 lamda ?
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 typeSystem.Collections.Generic.IEnumerable<ThingDetail>
我哪里出错了?
最佳答案
- 转换您收藏的
Thing
s 到Task<Thing>
的集合中s. - 然后使用
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
似乎返回一个 Task<Thing>
, 惯例是附加 Async
它的名字 - GetDetailAboutTheThingAsync
.
关于c# - 如何在返回集合的 lambda 中使用异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29821263/