【问题标题】:asp.net mvc 5 asynchronous action methodasp.net mvc 5 异步动作方法
【发布时间】:2015-04-01 04:56:29
【问题描述】:

我有以下带有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()方法。我应该对上面的代码做哪些修改?

【问题讨论】:

  • 你遇到了什么错误?
  • @utility 我没有收到任何错误。 SendMails() 方法是同步执行而不是异步执行。 return Json("success") 应该在当前线程上调用,SendMails() 应该异步执行..

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


【解决方案1】:

await 运算符应用于异步方法中的任务,以暂停该方法的执行,直到等待的任务完成。任务代表正在进行的工作。

听起来您不想等待 SendMails 的结果。将 async 和 await 视为使用异步 API 的工具。具体来说,能够“等待”“异步”任务的结果非常有用。但是,如果您不关心“异步”(例如 SendMails)任务的结果,那么您不需要“等待”结果(即布尔值)。

相反,您可以简单地使用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);
}

【讨论】:

  • 这正是我需要的,它似乎正在工作,但在SendContactFormUserMail() 函数中,我使用StreamReader 类从文本文件中读取电子邮件模板,但我得到@987654327 @异常..
  • 听起来你的变量之一是null。这个问题的答案可能会有所帮助:stackoverflow.com/questions/779091/…
  • 我正在使用HttpContext.Current.Server.MapPath() 方法来读取一个文本文件,并且在异步方法中这个值是null...
  • 您的 HttpContext.Current 为空,因为调用异步任务将使用无权访问 HttpContext.Current 的工作线程。有几个问题可能对您有所帮助。这是与此问题相关的问题/答案示例:stackoverflow.com/questions/19111218/…
  • 解决了我的问题,使用HostingEnvironment.ApplicationPhysicalPath; 获取应用程序物理路径并在服务器上测试了代码,现在工作速度非常快..感谢您的简单回答...
猜你喜欢
  • 2018-05-20
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多