I am using SmtpClient to sent out email. I create some function in Mail class:
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
MailStatus = Status.CANCEL;
MailStatusMessage = token + " Send canceled.";
}
else if (e.Error != null)
{
MailStatus = Status.ERROR;
MailStatusMessage = token + " " + e.Error.ToString();
}
else
{
MailStatus = Status.SENT;
MailStatusMessage = "Mail sent.";
}
mailSent = true;
}
public void SentEmail()
{
client = new SmtpClient(Host, Port);
client.Credentials = new NetworkCredential(UserName, Password);
MailAddress from = new MailAddress(MerchantEmail, MerchantName);
MailAddress to = new MailAddress(CustomerEmail);
MailMessage message = new MailMessage(from, to);
message.Body = EmailSubjectTemplate();
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = EmailSubjectTemplate();
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
client.SendAsync(message, "Sending message.");
message.Dispose();
}
In a form I call the function, before closing the form, but when waiting for the response from the SendCompletedCallback, the this.Close() will be executed:
Mail mail = new Mail();
mail.SentEmail();
this.Close();
How can I stop the form from closing before I get a response from SendCompletedCallback?
Option1
subscribe to this event from calling form as:
When you receive the complete event you can close the form
void m_OnMailSendComplete()
{
this.Close();
}
Option 2
when you create Mail object you can pass current form reference to it
then at the end of SendCompletedCallback you can close the form