简体   繁体   English

为什么我需要Dispose一个System.Net.Mail.MailMessage实例?

[英]Why do I need to Dispose a System.Net.Mail.MailMessage instance?

What unmanaged resources does it allocates that needs to be disposed? 它需要分配哪些非托管资源? Isn't it just a simple array of managed data? 它不仅仅是一个简单的托管数据阵列吗? So why disposing? 那么为什么要处置呢?

A mail message has attachments -> attachments are Streams -> Streams are to be disposed. 邮件消息包含附件 - >附件是Streams - > Streams将被丢弃。

Here is the decompiled Dispose method of MailMessage: 这是MailMessage的反编译Dispose方法:

    protected virtual void Dispose(bool disposing)
    {
        if (disposing && !this.disposed)
        {
            this.disposed = true;
            if (this.views != null)
            {
                this.views.Dispose();
            }
            if (this.attachments != null)
            {
                this.attachments.Dispose();
            }
            if (this.bodyView != null)
            {
                this.bodyView.Dispose();
            }
        }
    }

As a general rule a class should implement IDisposable if any of its contained children implement it. 作为一般规则,如果任何包含的子节点实现它,则类应该实现IDisposable。

A MailMessage can have attachments, an attachment is represented by MIME part which itself holds a Stream. MailMessage可以有附件,附件由MIME部分表示,MIME部分本身包含Stream。 This Stream needs closing as it might hold an unmanaged pointer to the underlying data. 此Stream需要关闭,因为它可能包含指向底层数据的非托管指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM