【发布时间】:2020-03-24 12:08:21
【问题描述】:
我的应用程序基本上是一个电子邮件客户端。它通常工作正常——没有问题或错误。当它向收件人发送电子邮件时,他们成功地收到了消息。但是,当该异步任务完成时,整个应用程序都会冻结。
我使用的一个修补程序是从 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
它为什么会导致应用程序冻结没有任何意义。
【问题讨论】:
-
试试
var response = await Task.Run(() => client.SendEmailAsync(Message));看看能不能解决问题。 -
顺便说一句,通过访问文件系统来初始化
static字段是一个非常糟糕的主意。如果 Documents.txt 文件丢失或被锁定,您的应用将严重崩溃。 -
感谢 Theodor 的推荐,文件系统的静态字段在主应用程序中进行评估,不会在此子表单中产生任何问题。
标签: c# asynchronous async-await sendgrid sendgrid-api-v3