【发布时间】:2012-11-21 23:00:35
【问题描述】:
我将如何编写一个由 1 +n 个异步调用 (await) 组成的异步控制器操作?例如。假设我需要首先检索对象Foo,它具有可变数量的Bars 标识符,我需要获取所有这些实体(为了这个问题,没有fetchBarsByFooId。我会使用@ 987654325@ 或者Parallel.For?
public async Task<ActionResult> Bars(int id) {
Foo foo = await this.FooProvider.GetFooAsync(id);
var bars = new ConcurrentQueue<Bar>();
// Sub-optimal version
foreach (int barId in foo.BarIDs) {
Bar bar = this.BarProvider.GetBar(barId);
bars.Enqueue(bar)
}
// Fetch each bar asynchronously and pass them to the view.
....
return View(bars.ToArray());
}
【问题讨论】: