I have a class that implements the IDisposable interface to host the private _MailMessage variable. In the same class, the async method is used, which uses the private IDisposable variable, namely async public Task<bool> Send My question is: will the usual implementation of IDisposable be a private variable after the asynchronous method completes? Here is an example of the class I'm talking about:
public class Email : IEmail { private readonly IEmailData _EmailData; private MailMessage _MailMessage = new MailMessage(); public Email(IEmailData emailData) { if (emailData == null) { throw new ArgumentNullException("emailData"); } if (String.IsNullOrEmpty(emailData.To)) { throw new ArgumentNullException("emailData.To"); } if (String.IsNullOrEmpty(emailData.From)) { throw new ArgumentNullException("emailData.From"); } if (String.IsNullOrEmpty(emailData.FromName)) { throw new ArgumentNullException("emailData.FromName"); } if (String.IsNullOrEmpty(emailData.Subject)) { throw new ArgumentNullException("emailData.Subject"); } if (String.IsNullOrEmpty(emailData.Body)) { throw new ArgumentNullException("emailData.Body"); } _EmailData = emailData; } async public Task<bool> Send() { return await Task.Run<bool>(() => { using (SmtpClient smtp = new SmtpClient()) { smtp.Send(_MailMessage); } return true; }); } #region "IDisposable implementation" public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Email() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_MailMessage != null) _MailMessage.Dispose(); } } #endregion }
I changed the implementation of IDisposable according to one of the answers suggesting not to use a destructor:
#region "IDisposable implementation" public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_MailMessage != null) _MailMessage.Dispose(); } }
c # idisposable async-await
Kees de wit
source share