应用程序在等待来自SendGrid的API返回代码时冻结



我的应用程序基本上是一个电子邮件客户端。它通常工作得很好——没有问题或错误。当它向收件人发送电子邮件时,他们就成功地收到了邮件。然而,当异步任务完成时,整个应用程序将冻结。

我使用的一个修补程序是从API响应中删除await关键字。这是有效的,使用这种方法,您无法获得确定消息是否成功发送的状态代码,因为您没有等待响应。

这是代码:

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace SendMailClass{
internal class FunctionCall{
#region Getting user info
static bool EmailHasBeenSend = false;
static string Documents = Environment.GetFolderPath(Environment.SpecialFolder
.MyDocuments) + "\Documents.txt";
static string UserName = File.ReadLines(Documents).Skip(0).Take(1).First();
static string UserEmail = File.ReadLines(Documents).Skip(1).Take(1).First();
#endregion
public static void SendFunction(string Recipient, string SubjectVariable,
string CC, string BCC, String Messange,string FileName,
string AttachmentPath)
{
Execute(Recipient, SubjectVariable ,CC,BCC, Messange ,FileName,
AttachmentPath).Wait();
}
static async Task Execute(string Recipient, string SubjectVariable,
string CC, string BCC, string Messange,string FileName,
string AttachmentPath)
{
#region Email Values
var apiKey = Environment.GetEnvironmentVariable("InMail_Api_Key");
var client = new SendGridClient(apiKey);
var from = new EmailAddress(UserEmail, UserName);
var subject = SubjectVariable == "" ? "(No subject)" : SubjectVariable;
var to = new EmailAddress(Recipient);
var plainTextContent = Messange == "" ? " " : Messange; ;
var htmlContent = Messange;
#endregion
var Message = MailHelper.CreateSingleEmail(from, to, subject,
plainTextContent, htmlContent);
#region Attachment
if (AttachmentPath != "") {
var bytes = System.IO.File.ReadAllBytes(AttachmentPath);
var File = Convert.ToBase64String(bytes);
Message.AddAttachment(FileName, File);
}
#endregion
/*
#region CC/BCC
if (CC != "") { 
Message.AddCcs("anemail@example.com");
}
if (BCC != ""){
Message.AddBccs("anemail@example.com")}
#endregion
*/
var response =await client.SendEmailAsync(Message);
//var response =client.SendEmailAsync(Message); ---> the hotfix
}
}
}

调试后,我得到的唯一结果来自调试器:

线程---已退出,代码为0(0x0(。

在断点处:

APIResponse等于NULL

它导致应用程序冻结的原因没有任何意义。

我提到我的上一个修补程序是:APIResponse =client.SendEmailAsync(Message);

我发现这是解决问题:

APIResponse = await client.SendEmailAsync(Message).ConfigureAwait(false);

在我确定这是最好的解决方案之前,我想对它进行更多的测试。到目前为止,回复是接受(如果电子邮件的形式正确(,如果连接未激活(没有互联网(,回复为

最新更新