If I wanted to write a non-blocking web api action by returning a Task object, I could do it with or without using the async keyword as such:
Using async
public async Task<HttpResponseMessage> Get()
{
Func<HttpResponseMessage> slowCall = () =>
{
Thread.Sleep(2000);
return Request.CreateResponse(HttpStatusCode.OK, "Hello world");
};
var task = Task<HttpResponseMessage>.Factory.StartNew(slowCall);
return await task;
}
Without using async
public Task<HttpResponseMessage> Get()
{
Func<HttpResponseMessage> slowCall = () =>
{
Thread.Sleep(2000);
return Request.CreateResponse(HttpStatusCode.OK, "Hello world");
};
var task = Task<HttpResponseMessage>.Factory.StartNew(slowCall);
return task;
}
They both work properly. However, every example I've seen (online and in books) on writing a web api action that returns a Task uses the async keyword. Granted, I understand that gives you more flexibility as it allows you to control what you want to "await" on and what not. But assuming your functionality could be effectively handled either way,
- Is there any advantage to using one approach vs the other?
- Should I always use the async keyword (and if so why)?
- Or is it irrelevant?
asyncis useful if you want to do anything more complicated than your current code.TaskFactory.StartNewin ASP.NET.Task.Run(or even worse,StartNew), you're just trading one thread for another. Let me turn the question around: what benefit do you get fromawaitwithTask.RunorStartNew?Task.Delayis a the usual example in such cases.