As for the Web API, you don't need the base class of the Async controller. All you have to do is wrap the return value in the Task.
For instance,
/// <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 use await-async to write even simpler 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); }
source share