我有一个GUI我必须导入一些文档,但是当我使用后台工作程序时,GUI挂起,因为我使用后台工作程序,所以不会发生这种情况,为什么会发生这种情况?请在下面找到代码..
void ImportNotes_ContextMenuStripItem_Click(object sender, EventArgs e)
{
if (!backgroundWorker_notesImport.IsBusy)
{
mainFrm.ProgressBar.Visible = true;
backgroundWorker_notesImport.RunWorkerAsync();
}
}
private void backgroundWorker_notesImport_DoWork(object sender, DoWorkEventArgs e)
{
ImportNotes();
}
private void backgroundWorker_notesImport_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
mainFrm.ProgressBar.Value = e.ProgressPercentage;
}
void ImportNotes() { }
答案 0 :(得分:0)
ImportNotes()
方法只需一步完成整个导入吗?
如果是这样,那么你仍然没有给UI做任何事情的机会。 example from the MSDN显示了应该如何使用它:
// This event handler is where the time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
}
}
您需要有一个循环,允许进行一些处理(在这种情况下为Sleep
)并调用ReportProgress
。