c# - 在返回语句之前未等待异步承诺
问题描述
昨天有这个问题,改了一些代码,又出现了……为什么两个邮件都不发送?没有等待承诺。有时会发送 1 封邮件,有时会发送 2 封邮件。Bool "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 阻止。这与错误的异步无关。
解决方案
Ok, the whole point of an asynchroneous call, is not to "wait" or delay performance. The method will just 'run'. Unless there is an exception raised in that method, there is nothing that would prevent the method from not get executed successfully.
Try adding a break-point and see why the messagesSent returns false sometimes, I am suspecting this line:
if (responseClient.StatusCode.ToString() == "202" && responseServer.StatusCode.ToString() == "202")
Is there any chance that the StatusCode might be returning a "200" as well?
推荐阅读
- c# - 如何使用 JavaScript 从 .NET Core 3.1 正确调用 HttpPost 方法,避免出现 400 错误
- saml-2.0 - ADFS 持久 ID 映射存储
- image-resizing - 如何根据原始测试图像大小调整预测的蒙版图像大小
- java - 如何使用 Spring Security 做一个 RESTful 登录 API?
- php - 带有输入字段的 Laravel 多个复选框
- arrays - 多个随机大小数组的内存分配
- c++ - C(avr-gcc 是带有类和新/删除的 C)- 不为微控制器上的非实例化类分配内存的最佳方法
- c# - 使用链接方法c#创建新变量时如何在内部类返回之间跳转
- kubernetes - Rancher:尽管 L7 Ingress 工作,L4 Balancer 仍停留在 Pending
- arrays - 字节数组值可以被覆盖吗?