Asp.net mvc 5 asynchronous action method

I have the following action method with async and await keywords:

 [HttpPost] public async Task<ActionResult> Save(ContactFormViewModel contactFormVM) { if (domain.SaveContactForm(contactFormVM) > 0)// saves data in database { bool result = await SendMails(contactFormVM);//need to execute this method asynchronously but it executes synchronously return Json("success"); } return Json("failure"); } public async Task<bool> SendMails(ContactFormViewModel contactFormVM) { await Task.Delay(0);//how to use await keyword in this function? domain.SendContactFormUserMail(contactFormVM); domain.SendContactFormAdminMail(contactFormVM); return true; } 

In the above code, after completing the database operation, I want to immediately return the Json() result, and then call the SendMails() method, which should be executed in the background. What changes should be made to the code above?

+5
source share
1 answer

The wait statement is applied to a task in an asynchronous method to pause the method until the expected task completes. The task is an ongoing job.

It seems you do not want to wait for the SendMails result. Think of async and wait as tools for using asynchronous APIs. In particular, it is very useful to be able to "wait" for the result of an "asynchronous" task. However, if you do not need the result of your "async" task (for example, SendMails), you do not need to "wait" for the result (ie Boolean).

Instead, you can simply use Task.Run to invoke your asynchronous task.

 [HttpPost] public async Task<ActionResult> Save(ContactFormViewModel contactFormVM) { if (domain.SaveContactForm(contactFormVM) > 0) {// saves data in database Task.Run(() => SendMails(contactFormVM)); return Json("success"); } return Json("failure"); } public void SendMails(ContactFormViewModel contactFormVM) { domain.SendContactFormUserMail(contactFormVM); domain.SendContactFormAdminMail(contactFormVM); } 
+9
source

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


All Articles