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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With