C# 使用取消令牌异步发送多封电子邮件

C# sending multiple emails asynchronously with cancellation token

我正在尝试使用 SendMailAsync 发送多条消息,并且我正在尝试传递取消令牌以在请求取消时中断发送过程。

static void Send(SmtpClientFactory factory, IEnumerable<MailMessage> messages)
{
    Task.WaitAll(SendAsync(factory, messages, CancellationToken.None));
}

static async Task SendAsync(SmtpClientFactory factory, IEnumerable<MailMessage> messages, CancellationToken token)
{
    await Task.Run(async () =>
    {
        using (SmtpClient smtpClient = factory())
        {
            foreach (MailMessage message in messages)
            {
                await smtpClient.SendMailAsync(message).ConfigureAwait(false);
            }
        }
    }, token);
}

当我使用非异步发送时,它陷入了死锁。如何同步发送消息并在时间到了时使用取消令牌取消?

您可以组合 CancellationToken.RegisterSmtpClient.SendAsyncCancel 来完成您需要的操作:

static async Task SendAsync(SmtpClientFactory factory, IEnumerable<MailMessage> messages, CancellationToken token)
{
    await Task.Run(async () =>
    {
        using (SmtpClient smtpClient = factory())
        {
            foreach (MailMessage message in messages)
            {
                token.ThrowIfCancellationRequested();

                using (token.Register(() => smtpClient.SendAsyncCancel()))
                {
                    await smtpClient.SendMailAsync(message).ConfigureAwait(false);
                }
            }
        }
    }, token);
}

请记住 SmtpClientofficially deprecated:

SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead

MailKit不仅是线程安全的,而且在消息构建方面也更加灵活,支持CancellationToken启动!