当我使用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?
发布评论