SmtpClient-什么是适当的生存期? [英] SmtpClient - What is proper lifetime?

查看:175
本文介绍了SmtpClient-什么是适当的生存期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating Windows Service that sends batches of emails every 5 minutes.

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

I want to send batches of 10-100 emails every 5 minutes. This is extreme edge case. Batches are sent every 5 minutes and normally consist of up to 10 emails.

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

I'm using SmtpClient from System.Net.Mail namespace.

SmtpClient对象的正确生存期是多少?
是否应在每次发送批次时创建一个?
还是应该在服务启动时创建一个,永远不要废弃它?

What is proper lifetime of SmtpClient object? Should I create one every time batch is send? Or should I create one on Service start and never dispose of it?

推荐答案

您应该始终使用使用

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

完成操作后,应始终处置所有实现IDisposable的东西.NET 4.0中的SmtpClient类实现IDisposable,因此请务必使用它!

You should always dispose of anything that implements IDisposable as soon as you are finished with it.The SmtpClient class in .NET 4.0 implements IDisposable so be sure to use it!

引用MSDN:

SmtpClient类没有Finalize方法,因此应用程序必须调用
进行Dispose才能显式释放资源。

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

如果发现自己正在执行异步相关任务,则可以为每个电子邮件创建一个新实例以防止自己被阻塞。可以使用以下内容。

If you find yourself doing async related tasks then you can make a new instance for each email to prevent blocking yourself.You can use the following.

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

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

如上所述,您可以重复使用同一客户端。如果将所有内容都放在同一线程上,建议您只使用一个客户端

As noted above you can reuse the same client. If you keep it all on the same thread I recommend you just use one client

MSDN状态:


SmtpClient类实现合并了SMTP连接,因此它
可以避免为与同一服务器的每个
消息重新建立连接的开销。 应用程序可能会重复使用同一
SmtpClient对象,将许多不同的电子邮件发送到同一SMTP
服务器和许多不同的SMTP服务器。

但是它继续说:


...结果,无法确定何时使用SmtpClient对象完成应用程序
并应对其进行清理。

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

因此,假设您在完成交易后将客户处置掉就可以了。

So assuming you dispose of your Client when complete it is fine.

下面有一些与SMTP相关的话题的讨论,我最近发现自己问了同样的问题

There is discussion of a number of SMTP related topics linked below as I recently found myself asking the same question

更多Stackoverflow上的内容:

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

相关阅读内容:

MSDN SmtpClient

实施完成nd处理清理托管资源

这篇关于SmtpClient-什么是适当的生存期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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