1

所以我一直在使用System.Net.Mail.MailMessage对象来发送电子邮件SmtpClient一段时间了。我注意到某个地方MailMessage实现了IDisposable,所以我总是在一个using块中使用它。

using(MailMessage msg = new MailMessage())
{
    msg.To = blah... etc;
    ...
    smtpclient.Send(msg);
}

从元数据中,您可以看到有关执行的信息MailMessage

// Summary:
//     Releases all resources used by the System.Net.Mail.MailMessage.
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void Dispose();
//
// Summary:
//     Releases the unmanaged resources used by the System.Net.Mail.MailMessage
//     and optionally releases the managed resources.
//
// Parameters:
//   disposing:
//     true to release both managed and unmanaged resources; false to release only
//     unmanaged resources.
protected virtual void Dispose(bool disposing);

但我想知道,为什么MailMessage实施IDisposable?它似乎与网络相关的项目没有任何关系,因为SmtpClient处理所有这些。

可能是由于可能持有附加文件的文件句柄吗?还有什么我忘记了吗?

4

5 回答 5

16

根据dotPeek,它正在处理它的附件和它的观点:

protected virtual void Dispose(bool disposing)
{
  if (!disposing || this.disposed)
    return;
  this.disposed = true;
  if (this.views != null)
    this.views.Dispose();
  if (this.attachments != null)
    this.attachments.Dispose();
  if (this.bodyView == null)
    return;
  this.bodyView.Dispose();
}
于 2011-12-13T23:09:58.683 回答
7

它实现了 IDisposable,因为它有实现 IDisposable 的子代。例如,Attachment 是一次性对象,因为附件可以是 Stream,大部分时间都需要处理。因此,在发送消息后,需要处理消息以处理附件(其中包含流)。

于 2011-12-13T23:08:42.000 回答
5

MailMessage类型有几个它拥有并实现的字段IDisposable。模式的正确实现IDisposable要求它还实现IDisposable并链接对这些字段的调用。特别是附件、视图和正文视图

于 2011-12-13T23:10:18.673 回答
4

如果您提供图像或附件,则需要在处理时对其进行清理。因此,在 using 中隐式或显式调用 dispose 是您应该做的事情。

通常,始终对实现 IDisposable 的任何对象调用 dispose。如果没有必要,他们不会实施它。

于 2011-12-13T23:09:05.853 回答
0

您可以查看原始源代码以准确了解它当前的功能。请参阅MailMessage.Dispose。我这里没有包含源代码,因为我不知道是否允许。

于 2014-07-31T00:13:58.780 回答