MrV*_*vis 3 c# asynchronous sendgrid async-await sendgrid-api-v3
我的应用程序基本上是一个电子邮件客户端。它通常工作正常\xe2\x80\x94,没有问题或错误。当它向收件人发送电子邮件时,他们会成功收到该消息。然而,当该异步任务完成时,整个应用程序就会冻结。
\n\nawait我使用的修补程序是从 API 响应中删除关键字。这是可行的,但是使用这种方法,您无法获取确定消息是否已成功发送的状态代码,因为您没有等待响应。
这是代码:
\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing SendGrid;\nusing SendGrid.Helpers.Mail;\n\nnamespace SendMailClass{\n internal class FunctionCall{\n\n #region Getting user info\n static bool EmailHasBeenSend = false;\n static string Documents = Environment.GetFolderPath(Environment.SpecialFolder\n .MyDocuments) + "\\\\Documents.txt";\n static string UserName = File.ReadLines(Documents).Skip(0).Take(1).First();\n static string UserEmail = File.ReadLines(Documents).Skip(1).Take(1).First();\n #endregion\n\n public static void SendFunction(string Recipient, string SubjectVariable,\n string CC, string BCC, String Messange,string FileName,\n string AttachmentPath)\n {\n Execute(Recipient, SubjectVariable ,CC,BCC, Messange ,FileName,\n AttachmentPath).Wait();\n }\n\n static async Task Execute(string Recipient, string SubjectVariable,\n string CC, string BCC, string Messange,string FileName,\n string AttachmentPath)\n {\n #region Email Values\n var apiKey = Environment.GetEnvironmentVariable("InMail_Api_Key");\n var client = new SendGridClient(apiKey);\n var from = new EmailAddress(UserEmail, UserName);\n var subject = SubjectVariable == "" ? "(No subject)" : SubjectVariable;\n var to = new EmailAddress(Recipient);\n var plainTextContent = Messange == "" ? " " : Messange; ;\n var htmlContent = Messange;\n #endregion\n\n var Message = MailHelper.CreateSingleEmail(from, to, subject,\n plainTextContent, htmlContent);\n\n #region Attachment\n if (AttachmentPath != "") {\n var bytes = System.IO.File.ReadAllBytes(AttachmentPath);\n var File = Convert.ToBase64String(bytes);\n Message.AddAttachment(FileName, File);\n }\n #endregion\n\n /*\n #region CC/BCC\n if (CC != "") { \n Message.AddCcs("anemail@example.com");\n }\n if (BCC != ""){\n Message.AddBccs("anemail@example.com")}\n #endregion\n */\n\n var response =await client.SendEmailAsync(Message);\n //var response =client.SendEmailAsync(Message); ---> the hotfix\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n调试后,我得到的唯一结果来自调试器:
\n\n\n\n\n线程 --- 已退出,代码为 0 (0x0)。
\n
并在断点处:
\n\n\n\n\nAPIResponse 等于NULL
\n
为什么会导致应用程序冻结没有任何意义。
\n我已经提到我的最后一个修补程序是:
APIResponse =client.SendEmailAsync(Message);
我发现这可以解决问题:
APIResponse = await client.SendEmailAsync(Message).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)
在确定这是最佳解决方案之前,我想对其进行更多测试。到目前为止,响应已被接受(如果电子邮件格式正确),如果连接未激活(无互联网),则响应为空。