Correct use of async and await in Asp.Net

Asked

Viewed 1,543 times

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 email I have to put the await in front and the return of the method has to be async Task, however while doing 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 would like to know if this is the ideal way to use the asynchronous method.

  • What have you done? Show me where you’re having trouble.

  • I’ll put the code, but it’s not presenting problems, I just wanted to know if the form I did, that in the end the return of Actionresult turns Task<Actionresult> is correct.

1 answer

5


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

Don’t necessarily need keyword async, just to return a task.

The implementation of the action will be more or less like this:

  • The request arrives and the controller is invoked
  • The various layers of the service are invoked until it reaches 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 sets that task aside, and the thread is free to serve new requests
  • When the task completes (i.e., when the e-mail is sent), the task continues (all the code that comes after the await) will be run by a threadpool thread.

See the following posts by Stephen Cleary:

  • Thanks for the clarification dcastro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.