Async / Await & AsyncController?

Do you need to inherit from AsyncController when you use Async / Await in your controller or will not be asynchronous if you use the controller? How about asp.net web api? I do not think there is an AsyncApiController. Currently, I just inherit from the controller and its work, but is it really isync?

+4
source share
2 answers

XML comment for AsyncController class in MVC 4 says

Provided for backward compatibility with ASP.NET MVC 3.

The class itself is empty.

In other words, you do not need it.

+6
source

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); } 
0
source

Source: https://habr.com/ru/post/1441870/


All Articles