【发布时间】:2015-04-01 03:20:30
【问题描述】:
我想在BackgroundWorker 的工作没有完成时显示一个“加载表单”(一个带有一些文本消息的表单加上一个样式设置为选取框的进度条)。当BackgroundWorker 完成后,加载表单必须自动关闭。虽然我确实使用了BackgroundWorker,但主线程应该等到它完成。我可以使用AutoResetEvent 做到这一点,但我注意到由于它确实阻塞了主线程,因此表单加载的进度条也被冻结了。
我的问题是:如何在后台运行进程并等待它完成时显示该表单而不冻结它?我希望它很清楚。
这是我当前的代码:
BackgroundWorker bw = new BackgroundWorker();
AutoResetEvent resetEvent = new AutoResetEvent(false);
//a windows form with a progressBar and a label
loadingOperation loadingForm = new loadingOperation(statusMsg);
//that form has a progressBar that's freezed. I want to make
// it not freezed.
loadingForm.Show();
bw.DoWork += (sender, e) =>
{
try
{
if (!e.Cancel)
{
//do something
}
}
finally
{
resetEvent.Set();
}
};
bw.RunWorkerAsync();
resetEvent.WaitOne();
loadingForm.Close();
MessageBox.Show("we are done!");
【问题讨论】:
-
Backgroundworker 不会停止主线程。如果你想做某事,你可以使用事件 progresschanged、runworkercompleted 等。只需使用调度程序对象来调用主线程的任何内容。
标签: c# multithreading winforms backgroundworker