c# - asp.net mvc 5异步 Action 方法

标签 c# asp.net asp.net-mvc asynchronous

我有以下带有 asyncawait 关键字的操作方法:

[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/

相关文章:

c# - 从二进制数据检索图像到图像字段

c# - 如何从整数列表中设置选择元素的值和文本值

asp.net-mvc - 使用带有操作参数的 ASP.NET MVC 子 Controller ?

c# - 带有 cookie 身份验证的 ASP.Net Core 2.2 : how to avoid page redirect when not authorized for API only controllers

c# - .Net - ProtocolType.IP、ProtocolType.IPv4 和 ProtocolType.IPv6 之间的区别

c# - 使用 XElement 进行 XML 解析

c# - 透明用户控件清晰背景

asp.net - 它应该是 WebAPI 还是 asmx

c# - ASP.NET MVC Ajax Actions 结果封装

c# - C# 和 PostgreSQL 中已有太多客户端