gpt4 book ai didi

c# - 在 Controller 中调用异步方法

转载 作者:IT王子 更新时间:2023-10-29 04:31:03 25 4
gpt4 key购买 nike

我有一个类似下面的 Controller :

public MyController : Controller
{
public ActionResult DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}

调用我的 Controller 时出现以下错误:

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.

现在我无法控制 CallSomeMethodWhichDoesAsyncOperations并且该方法本身不是异步的,但在内部会执行一些异步触发并忘记。我能做些什么来修复它?已尝试将 Controller 更改为 AsyncController和/或使 Controller 中的方法异步。

编辑:

当我第一次尝试使用 AsyncController 时,结果相同

public MyController : AsyncController
{
public ActionResult DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}

然后

public MyController : AsyncController
{
public async Task<ActionResult> DoSomething()
{
CallSomeMethodWhichDoesAsyncOperations();
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}

确实将异常更改为以下“异步模块或处理程序已完成,而异步操作仍在挂起。”

最佳答案

Now I dont have control over CallSomeMethodWhichDoesAsyncOperations and the method itself is not async but internally does some async fire and forget. What can I do to fix it?

联系编写它的人并让他们修复它。

说真的,这是最好的选择。对此没有好的解决办法 - 只有 hack。

你可以破解它像这样工作:

public MyController : Controller
{
public async Task<ActionResult> DoSomething()
{
await Task.Run(() => CallSomeMethodWhichDoesAsyncOperations());
return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
}
}

不推荐。此解决方案将工作推到后台线程,因此当async 操作恢复时,它们将没有HttpContext 等。此解决方案在仍有处理要完成时完成请求。如果服务器在错误的时间停止/回收,则此解决方案将无法正常运行。

只有一个合适的解决方案:更改 CallSomeMethodWhichDoesAsyncOperations

关于c# - 在 Controller 中调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13647346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com