【发布时间】:2016-05-03 05:52:57
【问题描述】:
我在一个 MVC5 应用程序中工作,它将处理一些密集的 IO 操作。所以我们正在转换方法以使用 async/await TPL 的东西。
在异步/等待更改之前,我注册了一个自定义 IAsyncActionInvoker,它将 Json ActionResult 更改为 JsonNet ActionResult,如下例所示:
Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?
当更改为使用永远不会执行 JsonNet ActionResult 的 async/await 任务时,问题就来了。有谁知道在迁移到 async/await Task 时如何维护这个实现?
public class CustomActionInvoker : AsyncControllerActionInvoker
{
protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
{
ActionResult invokeActionMethod = base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
if (invokeActionMethod is JsonResult)
{
return new JsonNetResult(invokeActionMethod as JsonResult);
}
return invokeActionMethod;
}
}
public class HomeController : Controller
{
// THIS WORKS!
public ActionResult Test()
{
return Json(new
{
Property1 = "blah",
Property2 = "test"
}, JsonRequestBehavior.AllowGet);
}
// THIS DOES NOT FIRE MY CUSTOM ACTION INVOKER
// IT RUNS THE DEFAULT
public async Task<ActionResult> Test()
{
await Task.Run(() =>
{
Thread.Sleep(1000);
});
return Json(new
{
Property1 = "blah",
Property2 = "test"
}, JsonRequestBehavior.AllowGet);
}
}
任何帮助将不胜感激!
【问题讨论】:
-
您是否尝试过在您的 CustomActionInvoker 上覆盖 BeginInvokeActionMethod 和 EndInvokeActionMethod?
-
我刚刚看到在阅读此评论后,将尝试覆盖这两个,看看我是否得到预期的结果,谢谢! @danludwig
-
我会回答这个问题,但显然我不能,所以在@danludwig 对我的问题发表评论后,我找到了正确答案。我假设由于 Begin/End 异步方法被认为是“旧的”,有利于 TPL async/await 方法,因此实现 async/await 模式将使我们不必重写 AsyncControllerActionInvoker 中的 Begin/End InvokeActionMethod 方法(认为它只是为了向后兼容)。所以答案是覆盖 EndInvokeActionMethod。
-
一旦您获得更多声誉,您就可以回来回答这个问题。很高兴我能帮你找到它。
标签: c# asp.net-mvc task-parallel-library async-await