async/await and the IDisposable interface

三世轮回 提交于 2019-12-05 03:07:16

You are doing it pretty fundamentally wrong. A good rule to keep in mind that if you think that you need a destructor then you're wrong 99.9% of the time. A destructor is only required if you have a private variable of an unmanaged type that needs to be released. You don't. The way that you can tell you are doing it wrong is when you find out that you are not actually doing anything at all if the disposing argument is false. Or in other words, the destructor doesn't actually do anything. So it isn't needed. Then you don't need the disposable pattern either.

There's more wrongness, you need to inherit the IDisposable interface to implement your own Dispose() method. You forgot.

Your Dispose() method needs to be called by the client code that creates an instance of your Email class. You cannot call it yourself, you don't know when the client code stops using your Email object. So that's a quick answer to your question, you cannot dispose yourself in the Send() method. There's no guarantee whatsoever that the client code will actually call it. You will have to leave it up to the client code to get it right.

I don't see anywhere you're explicitly disposing _MailMessage other than in Email.Dispose.

async doesn't do anything particularly magical with IDispose; the only thing you have to keep in mind is that async methods may return early.

So if you call it like this:

using (var email = new Email(...))
{
  await email.Send();
}

Then your calling code will (asynchronously) wait for Send to complete before disposing email. But if you call it like this:

Task task;
using (var email = new Email(...))
{
  task = email.Send();
}

Then your calling code will dispose email before Send completes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!