gpt4 book ai didi

c# - SMTP 发送邮件已取消

转载 作者:行者123 更新时间:2023-12-02 07:42:06 26 4
gpt4 key购买 nike

尝试发送邮件,但任务被取消。知道为什么吗?

public static Task SendAsync(this SmtpClient client, MailMessage message)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Guid sendGuid = Guid.NewGuid();

SendCompletedEventHandler handler = null;
handler = (o, ea) =>
{
if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid)
{
client.SendCompleted -= handler;
if (ea.Cancelled)
{
tcs.SetCanceled(); // TASK CANCELLED: Why?
}
else if (ea.Error != null)
{
tcs.SetException(ea.Error);
}
else
{
tcs.SetResult(null);
}
}
};

client.SendCompleted += handler;
client.SendAsync(message, sendGuid);
return tcs.Task;
}

调用者:

using( SmtpClient smtpClient = new SmtpClient() )
{
return smtpClient.SendAsync(msg);
}

预先感谢您的帮助!杰拉德

最佳答案

一个using语句将调用一个对象 Dispose完成执行 block 时的方法。调用smtpClient.SendAsync不使用await异步方法上将导致执行 block 结束并且 Dispose将被调用SmtpClient ,尽管SendAsync方法仍在执行,这解释了为什么一些邮件完成,因为有些可能会在处理对象之前完成,而另一些则不会。

这样做:

using (SmtpClient smtpClient = new SmtpClient())
{
await smtpClient.SendAsync(msg);
}

关于c# - SMTP 发送邮件已取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com