SmtpClient.SendMailAsync 方法线程安全吗? [英] Are the SmtpClient.SendMailAsync methods Thread Safe?

查看:21
本文介绍了SmtpClient.SendMailAsync 方法线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SmtpClient 类 指出实例成员不是线程安全的.如果并发调用 SendSendAsync.如果第一次调用尚未完成,这两种方法都会在第二次调用时抛出 InvalidOperationException.

The SmtpClient Class states that instance members are not thread safe. This can be seen if concurrent calls are made to Send or SendAsync. Both methods will throw a InvalidOperationException on the second call if the first has not yet completed.

.NET 4.5 中引入的方法 SendMailAsync 没有将 InvalidOperationException 列为抛出的异常.新的 .NET 4.5 方法是否实现了某种排队?Reflector 无法阐明此类的实现细节,因此我假设这已在本机方法中实现.

The method SendMailAsync, introduced in .NET 4.5, does not list InvalidOperationException as a thrown exception. Do the new .NET 4.5 methods implement some sort of queuing? Reflector isn't able to shed any light on the implementation details of this class, so I assume this has been implemented in native methods.

多个线程能否安全地在 SMTP 客户端的共享实例上调用 SendMessageAsync 方法?

Can multiple threads call the SendMessageAsync method on a shared instance of the SMTP client safely?

推荐答案

我不知道为什么使用 Reflector 对您不起作用.如果我反编译它,我会看到以下代码:

I'm not sure why using Reflector didn't work for you. If I decompile it, I see the following code:

[HostProtection(SecurityAction.LinkDemand, ExternalThreading=true)]
public Task SendMailAsync(MailMessage message)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    SendCompletedEventHandler handler = null;
    handler = delegate (object sender, AsyncCompletedEventArgs e) {
        this.HandleCompletion(tcs, e, handler);
    };
    this.SendCompleted += handler;
    try
    {
        this.SendAsync(message, tcs);
    }
    catch
    {
        this.SendCompleted -= handler;
        throw;
    }
    return tcs.Task;
}

如您所见,它是 SendAsync() 的简单 TAP 包装器.如果 SendAsync() 抛出异常,SendMailAsync() 只会重新抛出它.

As you can see, it's a simple TAP wrapper for SendAsync(). And if SendAsync() throws an exception, SendMailAsync() just rethrows it.

因此,结论是 SendMailAsync() 不是线程安全的,并且其异常记录不足.

So, the conclusion is that SendMailAsync() is not thread-safe and that its exceptions are underdocumented.

这篇关于SmtpClient.SendMailAsync 方法线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆