Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code inspection says I need to dispose object. Which one?

This is my function. I already wrapped both client and message into using clause and still get error when run code inspection. Error points to first using line:

public static void Send(MailItem mail)
        {
            var sender = Membership.GetUser(mail.CreatedBy);
            if (sender == null)
            {
                return;
            }

            using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) })
            {
                foreach (var recipient in mail.MailRecipients)
                {
                    var recipientX = Membership.GetUser(recipient.UserKey);
                    if (recipientX == null)
                    {
                        continue;
                    }

                    msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
                }

                msg.Subject = "[From: " + sender.UserName + "]" + mail.Subject;
                msg.Body = mail.Body;

                if (HttpContext.Current != null)
                {
                    msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" +
                                Environment.NewLine;
                    msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" +
                                ContextManager.CurrentAccount.AccountId + "&RUN=" + sender.UserName;
                }

                try
                {
                    using (var emailClient = new SmtpClient())
                    {
                        emailClient.Send(msg);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex);
                }
            }
        }

This is warning I get:

Warning 1 CA2000 : Microsoft.Reliability : In method 'Email.Send(MailItem)', object '<>g_initLocal0' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g_initLocal0' before all references to it are out of scope. C:\CodeWorkspace\Code\Utility\Email.cs 41

like image 365
katit Avatar asked Jun 24 '11 20:06

katit


People also ask

When should I use dispose?

The Dispose Method—Explicit Resource Cleanup The Dispose method generally doesn't free managed memory—typically, it's used for early reclamation of only the unmanaged resources to which a class is holding references. In other words, this method can release the unmanaged resources in a deterministic fashion.

How check object is disposed or not in C#?

The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed." msdn.microsoft.com/en-us/library/… @HansPassant: If an object implements IDisposable , one can call (IDisposable.

Why do we need dispose in C#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.


1 Answers

Your problem is this line:

using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) }) 

The initializer block { From = ... } is executed after the object is constructed and before the using block's internal try/finally begins.

If the MailAddress constructor (or its argument expressions, or the assignment to From if it is a property accessor) throws an exception, the MailMessage will not be disposed.

Change to:

using (var msg = new MailMessage()) 
{
    msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]);
    ...
}

The temporary <>g_initLocal0 variable is the name of the MailMessage before it gets assigned to msg.

like image 71
Random832 Avatar answered Nov 14 '22 05:11

Random832