Home > Net >  C# do i need to dispose mail that is sent async?
C# do i need to dispose mail that is sent async?

Time:08-24

Using a button to sent mail async and disposing of it in the task itself. Is this the correct way to do it?

Or do I need a catch inside the task and do I need a finally dispose on the button click?

And do I need to dispose of other things like the smtpclient? The mails don't have any attachments they are all just plain text.

private async void closeorder.Click(object sender, EventArgs e)
{
    try
    {
        await SendEmail();
    }
    catch (exception)
    {
        MessageBox.Show("mail has not been sent");
    }
}
private async Task SendEmail()
{
    SmtpClient smtpClient = new SmtpClient();
    MailMessage message = new MailMessage();

    if (System.IO.File.Exists(emailfile)
    {
        String[] Lines = System.IO.File.ReadAllLines(emailfile);
        foreach (string line in Lines)
            message.To.Add(line);
    }
    else
    {  
        System.IO.File.WriteAllText(emailfile,"");
        TextWriter Email = new StreamWriter(emailfile, true);
        Email.Writeline("[email protected]");
        Email.close();
    }

    try
    {
        MailAdress fromAddress = new MailAddress("[email protected]","order");
        smtpClient.Host "";
        smtpClient.Port xx;
        smtpClient.credentials = ("""");
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        message.From = fromAddress;
        message.Subject = "";
        message.IsBodyHtml = True;
        message.Body = Mybody();
        message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        await smtpClient.SendMailAsync(message);
    }
    finally 
    {
        message.Dispose();
    }
}

Sorry if formatting isn't the best typed on mobile.

CodePudding user response:

Both SmtpClient and MailMessage implement the IDisposable interface so you should dispose them. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=net-6.0

The fact it is in a asynchronous flow does not invalidate the fact you need to dispose properly those objects.

But you can avoid to use the try/catch/finally with the using keyword:

using(var smtpClient = new SmtpClient())
using(var message = new MailMessage()) 
{
  // Your code
}

It will generate for you (behing the scene) the try/catch/finally blocks and the call to dispose.

  • Related