我有一个WPF窗口,带有一个产生BackgroundWorker线程来创建和发送电子邮件的按钮。在此BackgroundWorker运行时,我想显示一个用户控件,显示一些消息,后面跟着一个动画“...”。该动画由用户控件中的计时器运行。当backgroundworker运行时计时器没有被调用
即使我的邮件发送代码位于BackgroundWorker上,用户控件中的计时器也永远不会被调用(当然,只有当Backgroundworker完成时,它才会失败)。
相关的代码在WPF窗口:
public void Show()
{
tb_Message.Text = Message;
mTimer = new System.Timers.Timer();
mTimer.Interval = Interval;
mTimer.Elapsed += new ElapsedEventHandler(mTimer_Elapsed);
mTimer.Start();
}
void mTimer_Elapsed(object sender, ElapsedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
int numPeriods = tb_Message.Text.Count(f => f == '.');
if (numPeriods >= NumPeriods)
{
tb_Message.Text = Message;
}
else
{
tb_Message.Text += '.';
}
}));
}
public void Hide()
{
mTimer.Stop();
}
任何想法,为什么它锁定了:
private void button_Send_Click(object sender, RoutedEventArgs e)
{
busyLabel.Show(); // this should start the animation timer inside the user control
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
string body = textBox_Details.Text;
body += "User-added addtional information:" + textBox_AdditionalInfo.Text;
var smtp = new SmtpClient
{
...
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}));
}
用户控件( “BusyLabel”)相关的代码?
您是否必须在UI线程上调用'worker_DoWork',因为我没有看到在那里调用的任何UIElements,也许删除'worker_DoWork'中的Dispatcher.Invoke将解决该问题。或将其更改为'Dispatcher.BeginInvoke' –
哎呀我砍了一些访问UI的代码。现在重新添加。 – akevan