Asp MVC and Web Api Async Controllers

I worked with Asp MVC 3, and an Async controller was created in my application with some methods like:

public void ActionAsync() { AsyncManager.OutstandingOperations.Increment(); AsyncManager.Parameters["someResult"] = GetSomeResult(); AsyncManager.OutstandingOperations.Decrement(); } public JsonResult ActionCompleted(SometResultModel someResult) { return Json(someResult, JsonRequestBehavior.AllowGet); } 

And now, when I work with MVC4 and Web Api, I need to create a controller with asynchronous actions, for example, in mvc 3. Currently, it looks like this:

 public Task<HttpResponseMessage> PostActionAsync() { return Task<HttpResponseMessage>.Factory.StartNew( () => { var result = GetSomeResult(); return Request.CreateResponse(HttpStatusCode.Created, result); }); } 

Is it a good idea to do asynchronous actions in web api like this, or is there some better way?

UPD Also, if I will use

 public async Task<HttpResponseMessage> ActionAsync() { var result = await GetSomeResult(); return Request.CreateResponse(HttpStatusCode.Created, result); } 

Will this full action work in the background thread? And how to make my GetSomeResult() function expected? It returns that Task<HttpResponseMessage> not expected.

+4
source share
1 answer

There is a big difference with your original action in MVC 3, where you basically free the client after calling the ActionAsync method (the client thread is freed, and it must call the ActionCompleted action after that to get the results). If this is what you are looking for, you need to implement asynchronous code with tasks on the client side.

The second version is to make the server asynchronous code, but the client thread will still wait for a response synchronously. waiting for GetResult will cause the server thread to return to the ASP.NET thread pool until the GetResult method returns something so that the thread can be reused with another request. This has nothing to do with background work. If you want to use the fire and forget approach, you need to use Task.Factory.StartNew (() => your code) or ThreadPool.QueueUserWorkItem (() => your code)

+2
source

All Articles