async
및 Task
을 await
으로 이해하려고합니다. 응용 프로그램이 제대로 작동하지 않았으므로 아직 제대로 작동하지 않을 수도 있습니다.비동기 작업 이해 및 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("[email protected]", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new SendGrid.Helpers.Mail.EmailAddress("[email protected]", "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();
}
를 지금은 내 코드 (가장 가능성이 끔찍한 관행을) 설명했다고, 더 나은 작업 비동기 이해하고 내가 달성하기 위해 시도하고있는 무슨 향상을 기대했다.
var iResponse = await client.SendEmailAsync(msg);
을 어떻게 기다려야 데이터베이스에 올바르게 저장할 수 있습니까? 응용 프로그램을 계속 허용 (사용자 환경을 방해하지 않음).
추가 정보가 필요한지 알려주세요.
실제로 SendGrid는'Wait()'을 사용 하시겠습니까? 컨트롤러를 비동기로 설정하고 호출을 '대기'해야하며 대기를 사용하여 차단하지 마십시오. – Crowcoder
다른 질문 @Clint를 확인해 보겠습니다. 감사합니다. – Derek
SendGrid에는 [시작하기] (https://app.sendgrid.com/guide/integrate/langs/csharp) @Crowcoder에 .Wait()이 있습니다. – Derek