昨天发生了此问题,更改了一些代码,然后又再次发生...为什么两个邮件都不发送?诺言没有等待。有时1,有时2封邮件发送。布尔“ messagesSent”有时还返回false,而应该返回true。
功能:
private async Task<bool> SendMails(string email, string name, string pdfPath, string imgPath)
{
var client = new SendGridClient(_config["SendGrid:Key"]);
bool messagesSent = false;
try
{
var messageClient = new SendGridMessage
{
From = new EmailAddress(_config["SendGrid:Recipient"]),
Subject = "Subject1",
HtmlContent = _textManager.Get("email-b")
};
var MessageServer = new SendGridMessage
{
From = new EmailAddress(_config["SendGrid:Recipient"]),
Subject = "Subject2",
HtmlContent = _textManager.Get("email-s")
};
messageClient.AddTo(email, name);
MessageServer.AddTo(email, name);
string[] fileListClient = new string[] { pdfPath };
string[] FileListServer = new string[] { pdfPath, imgPath };
foreach (var file in fileListClient)
{
var fileInfo = new FileInfo(file);
if (fileInfo.Exists)
await messageClient.AddAttachmentAsync(fileInfo.Name, fileInfo.OpenRead());
}
foreach (var file in FileListServer)
{
var fileInfo = new FileInfo(file);
if (fileInfo.Exists)
await MessageServer.AddAttachmentAsync(fileInfo.Name, fileInfo.OpenRead());
}
var responseClient = await client.SendEmailAsync(messageClient);
var responseServer = await client.SendEmailAsync(MessageServer);
if (responseClient.StatusCode.ToString() == "202" && responseServer.StatusCode.ToString() == "202")
{
messagesSent = true;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return messagesSent;
}
致电者:
bool sentMails = await SendMails(formCollection["email"], formCollection["name"], pdfPath, imgPath);
if (!sentMails)
{
errorMessage = "Error sending mails.";
succes = false;
}
编辑: 请求有效,呼叫已被ISP / MailServer阻止。这与错误的异步无关。
答案 0 :(得分:-1)
好的,异步调用的全部目的不是要“等待”或延迟性能。该方法将“运行”。除非该方法引发异常,否则没有什么可以阻止该方法无法成功执行的。
尝试添加一个断点,看看为什么有时候MessageSent返回false,我怀疑这行:
if (responseClient.StatusCode.ToString() == "202" && responseServer.StatusCode.ToString() == "202")
StatusCode是否也有可能返回“ 200”?