我有以下带有 async
和 await
关键字的操作方法:
[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;
}
在上面的代码中,一旦数据库操作完成,我想立即返回 Json()
结果,然后调用 SendMails()
方法,该方法应该在背景。我应该对上面的代码做哪些修改?
最佳答案
The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.
听起来您不想等待 SendMails 的结果。将 async 和 await 视为使用异步 API 的工具。具体来说,能够“等待”“异步”任务的结果非常有用。但是,如果您不关心“异步”(例如 SendMails)任务的结果,那么您不需要“等待”结果(即 bool 值)。
相反,您可以简单地使用 Task.Run调用您的异步任务。
[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);
}
关于c# - asp.net mvc 5异步 Action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383116/