【问题标题】:Why is my async function hanging when calling task.run function为什么调用 task.run 函数时我的异步函数挂起
【发布时间】:2015-07-09 16:56:09
【问题描述】:

我想使函数异步,因为我想将结果返回到 UI 并且不想让这个挂起,但无论如何都是这样。

谁能告诉我为什么会挂起?

public ActionResult Index()
{
    return View(FunctionThreeAsync().Result);
}

private async Task<MyType> FunctionThreeAsync()
{
    return await FunctionThree();
}

private Task<MyType> FunctionThree()
{
    return Task.Run<MyType>(() => { /* code */ });
}

【问题讨论】:

  • 返回视图(await FunctionThreeAsync());

标签: c# asynchronous async-await task-parallel-library task


【解决方案1】:

这个:

return View(FunctionThreeAsync().Result);

使您的代码陷入僵局。 You shouldn't be blocking on an async method。相反,将您的方法标记为async,使其返回Task&lt;T&gt;await 调用:

public async Task<ActionResult> DoStuffAsync()
{
    return View(await FunctionThreeAsync());
}

异步一直在进行。当你有一个异步方法时,它需要异步等待,而不是同步阻塞。这意味着在整个代码库中传播 async

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多