c# - Stop form from closing before getting response from SmtpClient.SendCompleted Event -


i using smtpclient sent out email. create function in mail class:

private void sendcompletedcallback(object sender, asynccompletedeventargs e) {     // unique identifier 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 = new mailaddress(merchantemail, merchantname);     mailaddress = 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 form call function, before closing form, when waiting response sendcompletedcallback, this.close() executed:

mail mail = new mail(); mail.sentemail(); this.close(); 

how can stop form closing before response sendcompletedcallback?

option1

public class mail  {     public delegate void mailsendcomplete();     public event mailsendcomplete onmailsendcomplete;     private void sendcompletedcallback(object sender, asynccompletedeventargs e)     {         // code          // call complete event         onmailsendcomplete();     }      public void sentemail()     {         // code      } } 

subscribe event calling form as:

mail m = new mail(); m.onmailsendcomplete += new mail.mailsendcomplete(m_onmailsendcomplete); m.sentemail(); 

when receive complete event can close form void m_onmailsendcomplete() { this.close(); }

option 2

when create mail object can pass current form reference

mail mail = new mail(this); 

then @ end of sendcompletedcallback can close form

public class mail  {     public form form { get; set; }     public mail(form  f)     {         form = f;     }      private void sendcompletedcallback(object sender, asynccompletedeventargs e)     {         // code          // close form         form.close();     } } 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -