Correct use of async and await in Asp.Net

3

I am creating an asynchronous method for sending Emails from the opening or changing of the object, but when calling the method of sending mail I have to put await in front and the return of the method has to be async Task, do this in the controller of my application I have to call the method also with await in front and put the return of the action async Task

I wonder if this is the ideal way to use the asynchronous method.

    
asked by anonymous 03.09.2015 / 20:24

1 answer

4

Yes, when using async I / O, all methods from that point to the controller must return a Task or Task<T> . It is custom to say "async all the way", which is code for "do not mix async code with blocking code".

They do not necessarily need the keyword async , just to return a task.

The execution of the action will look something like this:

  • The request arrives and the controller is invoked
  • The various layers of the service are invoked until the point where the email is sent using async I / O
  • This method returns a task
  • All other methods also return a task, including controller action
  • The framework puts this task aside, and the thread is free to serve new requests
  • When the task completes (ie, when the email is sent), the continuation of the task (all code that comes after await ) will be executed by a threadpool thread.

See the following Stephen Cleary posts:

03.09.2015 / 21:18