开发者

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 = theMessag开发者_运维问答e;
        _isSuccess = isSuccess;
        _errorMessage = errorMessage;
    }

    #endregion

    #region IDisposable Members

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

    #endregion
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜