我有一个Windows窗体应用程序,我在其中发送一个简单的电子邮件来测试ID。问题是picturebox的可见性属性不会改变。 有人能建议一个简单的解决方案吗?
我的按钮点击
private void BtnSend_Click(object sender, EventArgs e)
{
try
{
pbLoad.Visible = true;
sendemail();
pbLoad.Visible = false;
MessageBox.Show("Mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
发送电子邮件功能
public void sendemail()
{
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(
"myID@gmail.com", "mypassword");
MailMessage msg = new MailMessage();
msg.To.Add(txt_to.Text);
msg.From = new MailAddress("myID@gmail.com");
msg.Subject = txt_sub.Text;
msg.Body = txt_msg.Text;
// Attachment data = new Attachment(txt_attach.Text);
// msg.Attachments.Add(data);
// System.Threading.Thread.Sleep(2000);
client.Send(msg);
}
}
答案 0 :(得分:1)
因为你没有给主线程渲染它的机会。您的主要线程忙于发送邮件。您需要在另一个线程中发送邮件。喜欢Task.Run
。
使用Async/await功能并调用不会阻止调用线程的SmtpClient.SendMailAsync
。这样UI线程就有时间渲染图片框。
你的方法应该是这样的:
private async void BtnSend_Click(object sender, EventArgs e)
{
try
{
pbLoad.Visible = true;
await SendEmailAsync();
pbLoad.Visible = false;
MessageBox.Show("Mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public Task SendEmailAsync()
{
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(
"myID@gmail.com", "mypassword");
MailMessage msg = new MailMessage();
msg.To.Add(txt_to.Text);
msg.From = new MailAddress("myID@gmail.com");
msg.Subject = txt_sub.Text;
msg.Body = txt_msg.Text;
// Attachment data = new Attachment(txt_attach.Text);
// msg.Attachments.Add(data);
// System.Threading.Thread.Sleep(2000);
return client.SendMailAsync(msg);
}
答案 1 :(得分:1)
使用线程概念
private void BtnSend_Click(object sender, EventArgs e)
{
try
{
pbLoad.Visible = true;
Thread t=New Thread(sendemail);
t.start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void sendemail()
{
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(
"myID@gmail.com", "mypassword");
MailMessage msg = new MailMessage();
msg.To.Add(txt_to.Text);
msg.From = new MailAddress("myID@gmail.com");
msg.Subject = txt_sub.Text;
msg.Body = txt_msg.Text;
// Attachment data = new Attachment(txt_attach.Text);
// msg.Attachments.Add(data);
// System.Threading.Thread.Sleep(2000);
client.Send(msg);
this.Invoke(new MethodInvoker(Finished))
}
}
Private Void Finished()
{
pbLoad.Visible = false;
MessageBox.Show("Mail send");
}