我有一个多线程程序。我想启动新的BackgroundWorker
并暂停当前线程。然后我想在新的BackgroundWorker
恢复以前的线程。我用C#编程。
我有一个大项目,不能把我的代码放在这里。
这是我的示例代码!我不太确定它对你的项目有用,但这是我的想法。希望有帮助。
BackgroundWorker bwExportLogFile = new BackgroundWorker();
private void ExportLogFile() {
bwExportLogFile.DoWork += bwExportLogFile_DoWork;
bwExportLogFile.RunWorkerCompleted += bwExportLogFile_RunWorkerCompleted;
bwExportLogFile.ProgressChanged += bwExportLogFile_ProgressChanged;
bwExportLogFile.RunWorkerAsync();
bwExportLogFile.WorkerReportsProgress = true;
bwExportLogFile.WorkerSupportsCancellation = true;
}
void bwExportLogFile_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
if(some thing is true here){
bw.CancelAsync();
}
}
所以当你想再次在BackgroundWorker中运行线程时,只需调用:
bwExportLogFile.RunWorkerAsync();
您可以使用AutoResetEvent并使用WaitOne来保存父线程。从生成的线程调用AutoResetEvent.Set方法以恢复父(主)线程的执行。
childThread.Start();
autoResetEvent.WaitOne();
在孩子(产生的线程)
private void SpawnedThread()
{
//your code
autoResetEvent.Set(); //will resume the execution after WaitOne(), may be under some condition.
}
您可以使用overloaded version of WaitOne来提供最长的等待时间。执行将恢复Set方法直到给定时间才被调用。
尝试设置WorkerSupportsCancellation = true,在ProgressChanged事件中你可以这样做:
BackgroundWorker bw = sender as BackgroundWorker;
bw.CancelAsync();
bw.RunWorkerAsync();