我正在为C#版本9.27.0使用SendGrid客户端库。
唯一能让它发送电子邮件的方法是将Wait()
添加到我的方法的末尾。
据我所知,await
操作符承诺在异步方法完成后返回到代码中的位置。
但是为什么我需要添加Wait()
呢?这不是将异步方法转换为同步的吗?如果是这样,那么实现异步又有什么意义呢?
Program.cs
static void Main(string[] args) {
//var customerImport = new CustomerImport();
//customerImport.DoImport();
var mailClient = new MailClient();
var recipients = new List<string>();
recipients.Add("test@lobbycentral.com");
//Never sends an email
var response = mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false);
//Will send an email
mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false).Wait();
}
MailClient.cs
public async Task SendMail(string emailFrom, List<string> emailTo, string subject, string body, bool isPlainText) {
try {
var apiKey = Utils.GetConfigValue("sendgridAPIKey");
var emails = new List<EmailAddress>();
foreach (string email in emailTo) {
emails.Add(new EmailAddress(email));
}
var plainTextContent = "";
var htmlContent = "";
if (!isPlainText) {
htmlContent = body;
} else {
plainTextContent = body;
}
var message = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress(emailFrom, "LobbyCentral"), emails, subject, plainTextContent, htmlContent);
//if (metaData != null)
// message.AddCustomArgs(metaData);
foreach (string filename in FileAttachments) {
if (System.IO.File.Exists(filename)) {
using (var filestream = System.IO.File.OpenRead(filename)) {
await message.AddAttachmentAsync(filename, filestream);
}
}
}
foreach (PlainTextAttachmentM plainTextM in PlainTextAttachments) {
byte[] byteData = Encoding.ASCII.GetBytes(plainTextM.Content);
var attachment = new Attachment();
attachment.Content = Convert.ToBase64String(byteData);
attachment.Filename = plainTextM.AttachmentFilename;
attachment.Type = "txt/plain";
attachment.Disposition = "attachment";
message.AddAttachment(attachment);
}
var client = new SendGridClient(apiKey);
var response = await client.SendEmailAsync(message);
if (response.IsSuccessStatusCode) {
if (DeleteAttachmentsAfterSend && FileAttachments.Count > 0) {
foreach (string filename in FileAttachments) {
if (System.IO.File.Exists(filename)) {
System.IO.File.Delete(filename);
}
}
}
} else {
Utils.DebugPrint("error sending email");
}
} catch (Exception ex) {
throw new Exception(string.Format("{0}.{1}: {2} {3}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex.StackTrace));
}
}
发布于 2022-05-18 10:06:36
问题:,但为什么我需要添加Wait()
?这不是将异步方法转换为同步的吗?如果是这样,那么实现异步又有什么意义呢?
回答:,这不是强制性,而是Wait()
a Task
。做异步有什么意义?它给你两个很大的好处。
Task
,这意味着它是可接受的,这也意味着,您可以选择等待它,或者干脆忘记它,让threadPool线程调度和捕获任务,而不是在同一个线程中同步运行它。async/await
模式,这意味着可以优雅地避免阻塞当前线程。下面的代码显然会阻塞当前线程。
static void Main(string[] args)
{
.
.
//Will send an email
mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false)
.Wait(); // <- block the current thread until the task completes.
}
如果SendMail
是您可以触发的东西&忘记在您真正的代码库中,那么您就可以摆脱.Wait()
,继续前进,而无需检查Task
状态。但是您的应用程序应该已经启动并运行了一定的时间来完成预定的任务。如果不是,您最好考虑使用async/await
模式,而不是使用.Wait()
阻止您的宝贵线程。
static async Task Main(string[] args)
{
.
.
//Will send an email and get to know when the task is done.
await mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false);
}
https://stackoverflow.com/questions/72266300
复制相似问题