C# Asp MVC和Web Api异步控制器
我正在使用Asp MVC 3,在我的应用程序中,使用以下方法创建了Async controller:C# Asp MVC和Web Api异步控制器,c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,asp.net-web-api,C#,Asp.net Mvc,Asp.net Mvc 3,Asp.net Mvc 4,Asp.net Web Api,我正在使用Asp MVC 3,在我的应用程序中,使用以下方法创建了Async controller: public void ActionAsync() { AsyncManager.OutstandingOperations.Increment(); AsyncManager.Parameters["someResult"] = GetSomeResult(); AsyncManager.OutstandingOperations.Decrement(); } publi
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时,我需要创建一个具有MVC3中的异步操作的控制器。目前看来:
public Task<HttpResponseMessage> PostActionAsync()
{
return Task<HttpResponseMessage>.Factory.StartNew( () =>
{
var result = GetSomeResult();
return Request.CreateResponse(HttpStatusCode.Created, result);
});
}
公共任务PostActionAsync()
{
返回Task.Factory.StartNew(()=>
{
var result=GetSomeResult();
返回Request.CreateResponse(HttpStatusCode.Created,result);
});
}
在WebAPI中这样做是一个好主意还是有更好的方法
UPD。还有,如果我会用
public async Task<HttpResponseMessage> ActionAsync()
{
var result = await GetSomeResult();
return Request.CreateResponse(HttpStatusCode.Created, result);
}
公共异步任务ActionAsync()
{
var result=等待GetSomeResult();
返回Request.CreateResponse(HttpStatusCode.Created,result);
}
这个完整的动作在后台线程中有效吗?以及如何使我的
GetSomeResult()
函数成为可等待的函数?返回的结果是,任务
不可等待。与您在MVC 3中的原始操作有很大区别,在MVC 3中,您基本上是在调用ActionAsync方法后释放客户端(客户端线程被释放,之后它必须调用ActionCompleted操作才能获得结果)。如果这正是您想要的,那么您需要在客户端用任务实现异步代码
第二个版本是使服务器代码异步,但客户端线程仍将同步等待响应。Wait GetResult将使服务器线程返回ASP.NET线程池,直到GetResult方法返回某些内容,以便线程可以与其他请求一起重用。这与背景工作无关。如果要使用fire and forget方法,则需要使用Task.Factory.StartNew(()=>您的代码)或ThreadPool.QueueUserWorkItem(()=>您的代码)您能告诉我此操作的外观吗?我已经尝试过使用它,并且我的所有“POST”查询都返回“404”工厂。StartNew在这种情况下是完全错误的,因为除了当前处理当前请求的线程之外,您正在旋转一个额外的线程(或在线程池中安排一些额外的工作)。EventModel.PrepareModel是否返回任务?“EventModel.PrepareModel”是无效函数。所以,如果“Factory.StartNew”是错误的,我应该使用什么来发出异步请求?通过本主题中的操作解决