在 .NET 4.0 下使用 SmtpClient、SendAsync 和 Dispose 的最佳实践是什么 [英] What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

查看:40
本文介绍了在 .NET 4.0 下使用 SmtpClient、SendAsync 和 Dispose 的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然 SmtpClient 是一次性的,我对如何管理它有点困惑,尤其是当我使用 SendAsync 进行调用时.据推测,在 SendAsync 完成之前我不应该调用 Dispose.但是我应该称它为(例如,使用使用").该场景是一个 WCF 服务,它在进行调用时定期发送电子邮件.大多数计算速度很快,但发送电子邮件可能需要一秒钟左右的时间,因此最好使用异步.

I'm a bit perplexed on how to manage SmtpClient now that it is disposable, especially if I make calls using SendAsync. Presumably I should not call Dispose until SendAsync completes. But should I ever call it (e.g., using "using"). The scenario is a WCF service which mails out email periodically when calls are made. Most of the computation is fast, but the sending of email can take a second or so, so Async would be preferable.

我每次发送邮件时都应该创建一个新的 SmtpClient 吗?我应该为整个 WCF 创建一个吗?帮助!

Should I create a new SmtpClient each time I send mail? Should I create one for the entire WCF? Help!

更新 以防万一,每封电子邮件始终针对用户进行定制.WCF 托管在 Azure 上,Gmail 用作邮件程序.

Update In case it makes a difference, each email is always customized to the user. The WCF is hosted on Azure and Gmail is used as the mailer.

推荐答案

注意:.NET 4.5 SmtpClient 实现了 async awaitable 方法 SendMailAsync.对于较低版本,请使用 SendAsync,如下所述.

Note: .NET 4.5 SmtpClient implements async awaitable method SendMailAsync. For lower versions, use SendAsync as described below.

您应该始终尽早处理 IDisposable 实例.在异步调用的情况下,这是在消息发送后的回调上.

You should always dispose of IDisposable instances at the earliest possibility. In the case of async calls, this is on the callback after the message is sent.

var message = new MailMessage("from", "to", "subject", "body"))
var client = new SmtpClient("host");
client.SendCompleted += (s, e) => {
                           client.Dispose();
                           message.Dispose();
                        };
client.SendAsync(message, null);

SendAsync 不接受回调有点烦人.

It's a bit annoying the SendAsync doesn't accept a callback.

这篇关于在 .NET 4.0 下使用 SmtpClient、SendAsync 和 Dispose 的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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