Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to pass a System.Net.Mail.MailMessage object around on a delegate in C#?

I have made a small SmtpSender class which handles the sending of an Smtp MailMessage object. When the message has been sent or failed to send I raise a delegate that contains a 'response' object that has the original MailMessage that the user was trying to send along with a success/fail boolean and an error string. The user can then resubmit the MailMessage object to the sender class to try again if they wish.

What I want to know is... if I raise a delegate that contains an object with unmanaged resources, do I need to then dispose the object in the current scope? If so will calling Dispose on it in the current scope kill the object that the delegate function receives? I am concerned about memory leaks in the long run here.

Any advice or help would be much appreciated. Thanks in advance!

Dave

public delegate void SmtpSenderSentEventHandler(object sender, SmtpSendResponse theResponse);

public class SmtpSendResponse : IDisposable
{
    #region Private Members

    private MailMessage _theMessage;
    private bool _isSuccess;
    private string _errorMessage;

    #endregion

    #region Public Properties

    public MailMessage TheMessage
    {
        get { return _theMessage; }
        set { _theMessage = value; }
    }

    public bool IsSuccess
    {
        get { return _isSuccess; }
        set { _isSuccess = value; }
    }

    public string Error
    {
        get { return _errorMessage; }
        set { _errorMessage = value; }
    }

    #endregion

    #region Constructors

    public SmtpSendResponse(MailMessage theMessage, bool isSuccess)
        : this(theMessage, isSuccess, null)
    { }

    public SmtpSendResponse(MailMessage theMessage, bool isSuccess, string errorMessage)
    {
        _theMessage = theMessage;
        _isSuccess = isSuccess;
        _errorMessage = errorMessage;
    }

    #endregion

    #region IDisposable Members

    public void Dispose()
    {
        if (_theMessage != null)
        {
            _theMessage.Attachments.Dispose();
            _theMessage.Dispose();
        }
    }

    #endregion
}
like image 873
David Honess Avatar asked Nov 06 '22 02:11

David Honess


1 Answers

When you call dispose on an Object you say you're done with it and that it should go into a 'broken' state that can be cleaned up by the garbage collector. So once its disposed I wouldn't use it again. So only dispose it when you're done with it.

The last object to use/touch the class should dispose it. Don't dispose it early.

like image 148
CodingBarfield Avatar answered Nov 09 '22 11:11

CodingBarfield