Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

email

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

like image 954
Raphael Avatar asked Dec 12 '11 16:12

Raphael


People also ask

Does SmtpClient need to be disposed?

The SmtpClient class has no Finalize method. So an application must call Dispose to explicitly free up resources.

What is Net Mail SmtpClient?

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.


1 Answers

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.

like image 95
Muhammad Hasan Khan Avatar answered Sep 19 '22 15:09

Muhammad Hasan Khan