Do you have to inherit from AsyncController when you're using Async/Await in your controller or will it not truly be asynchronous if you use Controller? How about Asp.net web api? I don't think there is a AsyncApiController. Currently i'm just inheriting from controller and its working but is it truly async?
2 Answers
In terms of Web API, you don't need a Async controller base class. All what you need to do is to wrap your return value in a Task.
For example,
/// <summary>
/// Assuming this function start a long run IO task
/// </summary>
public Task<string> WorkAsync(int input)
{
return Task.Factory.StartNew(() =>
{
// heavy duty here ...
return "result";
}
);
}
// GET api/values/5
public Task<string> Get(int id)
{
return WorkAsync(id).ContinueWith(
task =>
{
// disclaimer: this is not the perfect way to process incomplete task
if (task.IsCompleted)
{
return string.Format("{0}-{1}", task.Result, id);
}
else
{
throw new InvalidOperationException("not completed");
}
});
}
In addition, in .Net 4.5 you can benefit from await-async to write even more simple codes:
/// <summary>
/// Assuming this function start a long run IO task
/// </summary>
public Task<string> WorkAsync(int input)
{
return Task.Factory.StartNew(() =>
{
// heavy duty here ...
return "result";
}
);
}
// GET api/values/5
public async Task<string> Get(int id)
{
var retval = await WorkAsync(id);
return string.Format("{0}-{1}", retval, id);
}