在从 SmtpClient.SendDone 事件获得响应之前停止关闭表单
本文关键字:表单 响应 SendDone SmtpClient 事件 在从 | 更新日期: 2023-09-27 18:36:24
我正在使用SmtpClient发送电子邮件。我在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();
}
在窗体中,我在关闭窗体之前调用该函数,但是在等待来自 SendCompleteCallback 的响应时,this 。关闭() 将被执行:
Mail mail = new Mail();
mail.SentEmail();
this.Close();
如何在收到来自 SendCompleteCallback 的响应之前阻止表单关闭?
如果用户决定强制关闭其计算机,则几乎无能为力。(关闭,任务杀死或其他什么)。
但是,您可以连接 Form_Closing
事件并将CloseEventArgs
内的 e.Cancel
属性更改为 true,也许可以使用一个消息框通知用户挂起的操作。
首先将全局变量添加到您的主窗体(或任何您称之为它)中,作为状态标志:
private bool eMailSentPendingComplete = false;
然后在您的SentMail
方法中,在客户端之后添加此行。SentAsync:
eMailSentPendingComplete = true;
在SendCompletedCallback
中将其重置为 false并在主窗体中连接窗体关闭事件:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(eMailSentPendingComplete == true)
{
DialogResult dr = MessageBox.Show("Pending email, do you wish to close?", MEssageBoxButtons.YesNo);
e.Cancel = (dr == DialogResult.Yes ? true : false);
}
}
同样在 FormClosing 事件中,您可以查看属性 e.CloseReason 以进行进一步优化。
选项1
public class Mail
{
public delegate void MailSendComplete();
public event MailSendComplete OnMailSendComplete;
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// your code
// finally call the complete event
OnMailSendComplete();
}
public void SentEmail()
{
// your code
}
}
通过调用表单订阅此事件:
Mail m = new Mail();
m.OnMailSendComplete += new Mail.MailSendComplete(m_OnMailSendComplete);
m.SentEmail();
收到完整事件后,您可以关闭表单 无效 m_OnMailSendComplete() { 这。关闭(); }
选项 2
创建 Mail 对象时,可以将当前表单引用传递给它
Mail mail = new Mail(this);
然后在发送完成回调结束时,您可以关闭表单
public class Mail
{
public Form form { get; set; }
public Mail(Form f)
{
form = f;
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// your code
// finally close the form
form.Close();
}
}