我正在使用 BackgroundWorker 线程来执行一个长任务(基本上是读取一个大的 xml 文件)。工作人员第一次按要求正常工作,但如果我上传第二个 xml 文件,使用相同的后台工作人员有时工作正常,但大多数情况下,后台工作人员的 RunWorkerCompleted 甚至在 DoWork 事件之前被触发。部分代码如下所示
private void openFile_Click(object sender, RoutedEventArgs e)
{
// Code removed for brevity
worker = new BackgroundWorker();
worker.RunWorkerAsync();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.WorkerReportsProgress = true;
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DataImport();
//worker.Dispose();
//worker.Disposed += new EventHandler(worker_Disposed);
//worker.DoWork -= worker_DoWork;
//worker.RunWorkerCompleted -= worker_RunWorkerCompleted;
//worker = null;
//GC.Collect(GC.GetGeneration(worker), GCCollectionMode.Forced);
}
worker 是一个全局定义的变量。我不明白这里有什么问题。请帮助