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

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

问题描述

我对现在该怎么管理SmtpClient,它是一次性有点困惑,特别是如果我做使用SendAsync调用。 presumably我不应该调用Dispose直到SendAsync完成。不过,我应该永远把它(例如,使用使用)。该方案是定期寄出电子邮件时调用了一个WCF服务。大部分的计算速度快,但电子邮件的发送可能需要一秒钟左右,所以异步将是preferable。

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.

推荐答案

您应该总是在最早的可能性处置的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 不接受回调。

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

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