gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:12:34 24 4
gpt4 key购买 nike

我有以下带有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com