SmtpClient - 什么是正确的生命周期?

SmtpClient - What is proper lifetime?

我正在创建 Windows 每 5 分钟发送一批电子邮件的服务。

我想每 5 分钟发送 10-100 封电子邮件。这是极端情况。每 5 分钟发送一次批次,通常最多包含 10 封电子邮件。

我正在使用来自 System.Net.Mail 命名空间的 SmtpClient。

SmtpClient 对象的正确生命周期是多少? 我应该在每次发送批次时创建一个吗? 或者我应该在服务启动时创建一个并且永远不要处理它吗?

您应该始终利用 using

using (var smtpClient = new SmtpClient())
{
    smtpClient.SendMail(message);
}

在大多数情况下,您应该始终在完成后立即处理任何实现 IDisposable 的东西,但是您应该始终检查文档以确保。 .NET 4.0中的SmtpClient class实现了IDisposable所以一定要用!

引用MSDN:

The SmtpClient class has no Finalize method, so an application must call Dispose to explicitly free up resources.

如果您发现自己在执行与异步相关的任务,那么您可以为每封电子邮件创建一个新实例以防止阻塞 yourself.You 可以使用以下内容。

var smtpClient = new SmtpClient();
smtpClient.SendCompleted += (s, e) => {
                           client.Dispose();
                           message.Dispose();
                        };
client.SendAsync(message, null);

根据要求 - 批量发送电子邮件的最佳选择

如上所述,您可以重复使用同一个客户端。如果你把它们都放在同一个线程上,我建议你只使用一个客户端

MSDN 声明:

The SmtpClient class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same SmtpClient object to send many different emails to the same SMTP server and to many different SMTP servers.

然而它接着说:

...As a result, there is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.

因此假设您在完成后处置您的 Client 就可以了。


下面链接了一些与 SMTP 相关的主题的讨论,因为我最近发现自己也在问同样的问题

来自 Whosebug 的更多内容:

What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

How to dispose objects having asynchronous methods called?

相关阅读:

MSDN SmtpClient

Implementing Finalize and Dispose to clean up managed resources

首先,在需要时使用任何对象是一个很好的做法,除非您需要在整个应用程序中使用它。

其次,您应该在每次需要时创建 SmtpClient 的对象并妥善处理它,为此使用上面 Glitch100 描述的 using 标签。

 using (var smtpClient = new SmtpClient())
 {
     smtpClient.SendMail(message);
 }

从 .NET 4.0 开始,SmtpClient 会合并连接,因此您可能会继续使用它一段时间。最好在发送完一批后处理它。

来自 MSDN:https://msdn.microsoft.com/en/us/library/system.net.mail.smtpclient(v=VS.100).aspx

The SmtpClient class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same SmtpClient object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.