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

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

问题描述

借助 SmtpClient类指出实例成员不是线程安全的。这可以并发如果调用来发送或的 SendAsync 。这两种方法都将抛出一个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.

该方法 SendMailAsync ,介绍了.NET 4.5,不列出出现InvalidOperationException作为抛出异常。做新的.NET 4.5的方法实现某种排队?反射无法摆脱这个类的实现细节的光,所以我想这已经在本地方法中实现。

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.

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

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

推荐答案

我不知道为什么使用反射不为你工作。如果我反编译它,我看到下面的code:

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;
}

正如你所看到的,它是一个简单的TAP包装SendAsync()。如果 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()是不是线程安全并其异常underdocumented。

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

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

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