【发布时间】:2013-04-22 19:59:27
【问题描述】:
我正在使用 Asp MVC 3,并在我的应用程序中创建了异步控制器,其中一些方法如下:
public void ActionAsync()
{
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["someResult"] = GetSomeResult();
AsyncManager.OutstandingOperations.Decrement();
}
public JsonResult ActionCompleted(SometResultModel someResult)
{
return Json(someResult, JsonRequestBehavior.AllowGet);
}
现在,当我使用 MVC4 和 Web Api 时,我需要使用 mvc 3 中的异步操作创建控制器。目前它看起来像:
public Task<HttpResponseMessage> PostActionAsync()
{
return Task<HttpResponseMessage>.Factory.StartNew( () =>
{
var result = GetSomeResult();
return Request.CreateResponse(HttpStatusCode.Created, result);
});
}
像这样在 web api 中进行异步操作是个好主意,还是有更好的方法存在?
UPD。另外,如果我会使用
public async Task<HttpResponseMessage> ActionAsync()
{
var result = await GetSomeResult();
return Request.CreateResponse(HttpStatusCode.Created, result);
}
这个完整的动作会在后台线程中工作吗?以及如何让我的GetSomeResult() 函数可以等待?返回 Task<HttpResponseMessage> 不可等待。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-web-api