I have a winforms application from which the user can send an email. This email is sent async and not awaited (fire and forget)
The method calling the email async instantiates a class (EmailSender) which does all of the work of composing the email, sending it and logging the result in the database. I expect that wrapping EmailSender in a using statement will create problems with resources still working async trying to complete. However, if I just instantiate the class and call EmailSender.Send(), the resources will not be properly disposed.
What is the best way to proceed here while still managing the resources properly. Am I better of throwing all of this into static methods which manage their own resources or do I completely misunderstand the issue here
//Fire and forget
EmailSender es = new EmailSender(itemId);
es.Send();
public class EmailSender
{
public EmailSender(int ItemId)
{
//initialise stuff
}
public async void SendAsync()
{
string emailContent = getEmailContent();
using (MailMessage mail = new MailMessage())
{
using (SmtpClient client = emailManager.getSMTPSettings())
{
try
{
string fromSender = emailManager.getEmailFrom();
if (!string.IsNullOrEmpty(fromSender)) mail.From = new MailAddress(fromSender);
//etc
await client.SendMailAsync(mail);
}
catch
{ //log to db}
}
}
}
}
private string getEmailContent()
{
return "content";
}
}
EDIT: I want the async code to continue in the background after the form is closed and users move through to different parts of the application.