Why do I need to Dispose a System.Net.Mail.MailMes

2019-01-08 01:57发布

What unmanaged resources does it allocates that needs to be disposed? Isn't it just a simple array of managed data? So why disposing?

标签: c# email
2条回答
我命由我不由天
2楼-- · 2019-01-08 02:11

A mail message has attachments -> attachments are Streams -> Streams are to be disposed.

Here is the decompiled Dispose method of MailMessage:

    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.

查看更多
时光不老,我们不散
3楼-- · 2019-01-08 02:24

A MailMessage can have attachments, an attachment is represented by MIME part which itself holds a Stream. This Stream needs closing as it might hold an unmanaged pointer to the underlying data.

查看更多
登录 后发表回答