c# - 如何在返回集合的 lambda 中使用异步

标签 c# asp.net-mvc linq asynchronous lambda

我有一个异步“上游”方法。我正在尝试遵循最佳实践并在堆栈中一直采用 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 type System.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/

相关文章:

c# - 尝试更好地使用 Visual Studio!我如何找到有关排序方法的帮助?

c# - BackgroundCssClass 未与 ModalpopupExtender 一起应用

asp.net-mvc - GDI+ 中发生一般性错误

c# - 什么时候应该将集合循环转换为 Linq 语句?

c# - 林克 : Checking how many times the same value consecutively

c# - 使用正则表达式提取组并在一行中构建 URL

c# - 我们目前无法使用您的 PayPal 帐户处理您的付款

c# - 如何在 ASP.NET MVC 5 Controller 中返回 http 中的字符串?

asp.net-mvc - 如何将 http-request 转换为正确的对象?

c# - 使用 Linq 每次迭代选择多个项目?