Reputation: 1511
I have a web api call that I want to get great throughput on so I am wrapping the I/O with a Task in the hopes to make it async. However, I am not sure that it does want I looking for.
public HttpResponseMessage Post([FromBody]DataRequest request)
{
Task.Factory.StartNew(() =>
{
service.SendRequestToQueue(request);
});
return Request.CreateResponse(HttpStatusCode.Accepted);
}
I Feel like this is not the right way to do this. It does get the I/O off the the requesting thread but is still handled by a thread in the application and not the kernel. Am I right? Is there a better way to do this other then making async and await all the way down?
Upvotes: 2
Views: 817
Reputation: 456417
The correct solution, as @Servy commented, is to use async
all the way down. In particular, on ASP.NET, you should avoid Task.Run
and Task.Factory.StartNew
. As you suspected, using await
with a task queued to the thread pool will not give you any scalability benefit at all.
Your code as it currently stands returns the response while continuing to process the request in-memory. This is extremely dangerous, as I explain on my blog and in a recent CodeMash talk (see the slides under the "Gotchas" section entitled "Returning Early").
Upvotes: 1