我需要在后台工作中运行一个耗时的过程,在这个过程中我也需要打开一个窗口。所有工作都很好但是当我在该过程中调用UI时,它不允许我在新窗口中工作它只是显示等待,当我取消后台工作程序时它不会取消,尽管我启用了workersupportcancel。这是我的代码
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
runCheck();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
}
private void newBtncheck_Click(object sender, RibbonControlEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void newBtncheck_Click(object sender, RibbonControlEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void btnStop_Click(object sender, RibbonControlEventArgs e)
{
this.backgroundWorker1.CancelAsync();
}
答案 0 :(得分:3)
您需要在调用表单的BeginInvoke()
中包装打开新表单的代码。
将其放入backgroundWorker1_DoWork()
方法:
BeginInvoke(new Action(()=>{
// place code to open new form here, for example new MyNewForm().Show()
}));
这假设您的backgroundWorker1_DoWork()
是您的主要表单类的成员。如果没有,您需要明确指定主表单的实例:mainFormInstance.BeginInovoke(...)
答案 1 :(得分:0)
您可以使用Dispatcher
要求UI线程打开对话框:(来自here)
this.Dispatcher.BeginInvoke(new Action(() => ProgressDialog.ShowDialog()));