处置SmtpClient在SendComplete? [英] Dispose SmtpClient in SendComplete?

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

问题描述

当我使用SmtpClient的SendAsync发送电子邮件,我该如何正确处置 smtpclient 实例?

When I use SmtpClient's SendAsync to send email, how do I dispose the smtpclient instance correctly?

让我们说:


MailMessage mail = new System.Net.Mail.MailMessage()
{
   Body = MailBody.ToString(),
   IsBodyHtml = true,
   From = new MailAddress(FromEmail, FromEmailTitle),
   Subject = MailSubject
};
mail.To.Add(new MailAddress(i.Email, ""));
SmtpClient sc = new SmtpClient(SmtpServerAddress);
//Add SendAsyncCallback to SendCompleted
sc.SendCompleted += new SendCompletedEventHandler(SendAsyncCallback);
//using SmtpClient to make async send (Should I pass sc or mail into SendAsyncCallback?)
sc.SendAsync(mail, sc);

SendAsyncCallback 方法,我应该叫 sc.Dispose() mail.Dispose()

我查MSDN文档,其中一个例子调用MailMessage.Dispose(),但将在Dispose方法也处置 SmtpClient 实例?

I checked MSDN document, one example calls MailMessage.Dispose(), but will this dispose method also dispose the SmtpClient instance?

非常感谢。

推荐答案

您应该处理这两个 MAILMESSAGE SmtpClient SendAsyncCallback

You should dispose both the MailMessage and the SmtpClient in SendAsyncCallback.

在处置MAILMESSAGE不会自动处置SmtpClient(因为你可能想用相同的SmtpClient发送两个消息,你不会希望客户端为你设置在第一条消息尽快处理)。

Disposing the MailMessage will not dispose the SmtpClient automatically (because you might want to send two messages with the same SmtpClient, and you wouldn't want the client to be disposed as soon as you disposed the first message).

这篇关于处置SmtpClient在SendComplete?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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