Note that there are some explanatory texts on larger screens.

plurals
  1. POasync/await and the IDisposable interface
    text
    copied!<p>I have a class which implements the IDisposable interface to dispose a private variable <code>_MailMessage</code> The same class has a async method that makes use of the private IDisposable variable, namely <code>async public Task&lt;bool&gt; Send</code> My question is: Will the normal IDisposable implementation dispose the private variable after the async method completes? Here is an example of the class I am talking about:</p> <pre><code>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&lt;bool&gt; Send() { return await Task.Run&lt;bool&gt;(() =&gt; { 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 } </code></pre> <p>I have changed the IDisposable implementation according to one of the answer that suggest not to use a destructor:</p> <pre><code>#region "IDisposable implementation" public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_MailMessage != null) _MailMessage.Dispose(); } } #endregion </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload