我有一个实现 IDisposable 接口来处理私有变量_MailMessage
的类同一个类有一个使用私有 IDisposable 变量的异步方法,即async public Task<bool> Send
我的问题是:普通的 IDisposable 实现会在异步方法完成后处理私有变量吗?这是我正在谈论的课程的示例:
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
}
我已经根据建议不要使用析构函数的答案之一更改了 IDisposable 实现:
#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