Question

I have an Email class that has a Send method that optionally takes an SmtpClient and sends an email asynchronously using SendAsync. If no SmtpClient is supplied to this method, it instantiates a default SmtpClient and uses that to send the email. Inside the Send function, I provide a SendCompleted callback which disposes of the MailMessage and the default SmtpClient if one was not supplied to the method.

So when I am supplying the SmtpClient, how do I go about disposing it?

I can't dispose of it inside Send because it may be used for sending other emails, plus I figure it's the responsibility of the thing that instantiated the passed in SmtpClient to dispose of it again. Is it possible to add multiple SendCompleted callbacks to the SmtpClient that run after each other?

Was it helpful?

Solution

There are two major ways of going about destroying your SmtpClient objects.

  1. The SmtpClient manages its own lifetime (i.e. destroys itself when the time comes). This is easiest if each SmtpClient is used for only one email, but it can be made to work for multiple, if SmtpClient knows how many emails it sent and it can be guaranteed that the SendCompleted callback is invoked a corresponding number of times.
  2. An outside component manages the lifetime of SmtpClient (this can be the object that created SmtpClient or some other object). In this case, the SmtpClient needs to inform the object responsible for managing its lifetime about the SendCompleted callback being invoked. This is usually done by invoking a callback on that object from within SendCompleted.
Licensed under: CC-BY-SA with attribution
scroll top