首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么在控制台应用程序中使用SendGrid C#客户端库发送电子邮件时需要使用Wait

为什么在控制台应用程序中使用SendGrid C#客户端库发送电子邮件时需要使用Wait
EN

Stack Overflow用户
提问于 2022-05-16 22:33:59
回答 4查看 331关注 0票数 4

我正在为C#版本9.27.0使用SendGrid客户端库。

唯一能让它发送电子邮件的方法是将Wait()添加到我的方法的末尾。

据我所知,await操作符承诺在异步方法完成后返回到代码中的位置。

但是为什么我需要添加Wait()呢?这不是将异步方法转换为同步的吗?如果是这样,那么实现异步又有什么意义呢?

Program.cs

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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));
    }
}
EN

Stack Overflow用户

发布于 2022-05-18 10:06:36

问题:,但为什么我需要添加Wait()?这不是将异步方法转换为同步的吗?如果是这样,那么实现异步又有什么意义呢?

回答:,这不是强制性,而是Wait() a Task。做异步有什么意义?它给你两个很大的好处。

  1. 您可以返回Task,这意味着它是可接受的,这也意味着,您可以选择等待它,或者干脆忘记它,让threadPool线程调度和捕获任务,而不是在同一个线程中同步运行它。
  2. 您可以使用async/await模式,这意味着可以优雅地避免阻塞当前线程。

下面的代码显然会阻塞当前线程。

代码语言:javascript
运行
复制
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()阻止您的宝贵线程。

代码语言:javascript
运行
复制
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);
}
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72266300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档