提问者:小点点

了解异步任务并使用SendGrid等待[重复]


我正在尝试用来理解,但不确定我是否完全理解,因为我的应用程序没有按照我想象的方式响应。

我有一个MVC项目,在一个控制器内部是一个在保存上运行的方法。这个方法做了一些事情,但我主要关注的是向SendGrid发送电子邮件。

[HttpPost]
[ValidateAntiForgeryToken]
private void SaveAndSend(ModelView model)
{
    //This is never used, but is needed in "static async Task Execute()"
    ApplicationDBContext db = new ApplicationDBContext();

    //First try (like the SendGrid example)
        Execute().Wait();
        //More code, but wasn't being executed (even with a breakpoint)
        //...


    //Second try, removed the .Wait()
        Execute();
        //More code and is being executed (good)
        //...
}

内部执行():

static async Task Execute()
{
    var apiKey = "REMOVED";
    var client = new SendGridClient(apiKey);
    var from = new SendGrid.Helpers.Mail.EmailAddress("example@example.com", "Example User");
    var subject = "Sending with SendGrid is Fun";
    var to = new SendGrid.Helpers.Mail.EmailAddress("example@example.com", "Example User");
    var plainTextContent = "and easy to do anywhere, even with C#";
    var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
    var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
    var iResponse = await client.SendEmailAsync(msg);

    //The above ^ is executed (sent to SendGrid successfuly)

    //The below is not being executed if I run the code with no breakpoints
    //If I set a breakpoint above, I can wait a few seconds, then continue and have the code below executed

    //This is an Object I have to save the Response from SendGrid for testing purposes
    SendGridResponse sendGridResponse = new SendGridResponse
    {
        Date = DateTime.Now,
        Response = JsonConvert.SerializeObject(iResponse, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore })
    };

    //This is needed to save to the database, was hoping to avoid creating another Context
    ApplicationDBContext db = new ApplicationDBContext();

    db.SendGridResponses.Add(sendGridResponse);
    db.SaveChanges();

}

现在我已经概述了我的代码(很可能是可怕的实践),我希望更好地理解异步任务并改进我正在尝试完成的工作。

我如何才能等待并将其正确保存到我的数据库中。允许应用程序继续(而不是中断用户体验)。

请让我知道我是否应该包括更多的信息。


共1个答案

匿名用户

通过返回,然后返回调用,而不是返回,可以使您的控制器

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<IActionResult> SaveAndSend(ModelView model)
 {
      //This is never used, but is needed in "static async Task Execute()"
      ApplicationDBContext db = new ApplicationDBContext();

      // Await the Execute method call, instead of Wait()
      await Execute();
    .....
}

相关问题