我正在尝试理解async
,但不确定我是否完全理解它,因为我的应用程序没有按照我认为的方式响应Task
。await
我有一个 MVC 项目,控制器内部是一个在 Save 上运行的方法。这个方法做了一些事情,但我关注的主要项目是向 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();
}
现在我已经概述了我的代码(很可能是可怕的做法),我希望能够更好地理解 async Task 并改进我试图完成的工作。
如何等待var iResponse = await client.SendEmailAsync(msg);
并将其正确保存到我的数据库中。允许应用程序继续(不中断用户体验)。
如果我应该包含更多信息,请告诉我。