是否可以在C#中的委托上传递System.Net.Mail.MailMessage对象?

Dav*_*ess 5 c# memory memory-leaks smtp mailmessage

我做了一个小的SmtpSender类来处理发送Smtp MailMessage对象.当消息发送或发送失败时,我引发一个包含"响应"对象的委托,该对象具有用户尝试发送的原始MailMessage以及成功/失败布尔值和错误字符串.然后,用户可以将MailMessage对象重新提交给sender类,以便在需要时再次尝试.

我想知道的是......如果我提出一个包含非托管资源的对象的委托,那么我是否需要在当前范围内处理该对象?如果是这样,在当前作用域中调用Dispose会杀死委托函数接收的对象吗?从长远来看,我担心内存泄漏.

任何建议或帮助将不胜感激.提前致谢!

戴夫

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
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*eld 2

当你对一个对象调用 dispose 时,你就说你已经完成了它,并且它应该进入可以由垃圾收集器清理的“损坏”状态。所以一旦处理掉我就不会再使用它。因此,只有在用完后才将其丢弃。

最后一个使用/接触该类的对象应该处置它。不要过早丢弃它。