处置SmtpClient在SendComplete?

编程入门 行业动态 更新时间:2024-10-26 15:14:57
本文介绍了处置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?

本文发布于:2023-08-07 10:23:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1318602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SmtpClient   SendComplete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!