在win表单应用程序中,我有一个如下所示的线程数组:
bool stop = false; Thread[] threads = new Thread[10]; for (int i = 0; i < threads.Length; i++) threads[i] = new Thread(new ThreadStart(Job)); // How to make sure all threads have exited,when the boolean = false void Job() { while (!stop) // Do something }
现在,如果用户按下STOP,则stop的布尔值将设置为true,因此线程将一个接一个地退出Job方法.如何确保退出所有线程?
注意:我的情况需要传统的线程,TaskLibrary不适合我的场景.
解决方法
您是否考虑过使用
BackgroundWorkers?你说“传统线程”..我不完全确定你的意思所以我不知道这是否是一个有效的提议,但在这里它是无论如何,以防Join()无法解决你的问题
BackgroundWorker[] workers = new BackgroundWorker[10]; bool allThreadsDone = false; // initialize BackgroundWorkers for (int i = 0; i < 10; i++) { workers[i] = new BackgroundWorker(); workers[i].WorkerSupportsCancellation = true; workers[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); workers[i].DoWork += new DoWorkEventHandler(AlgorithmsUI_DoWork); workers[i].RunWorkerAsync(); } // thread entry point..DoWork is fired when RunWorkerAsync is called void AlgorithmsUI_DoWork(object sender,DoWorkEventArgs e) { while (!stop) // do something } // this event is fired when the BGW finishes execution private void worker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) { bool threadsStillRunning = false; foreach (BackgroundWorker worker in workers) { if (worker.IsBusy) { threadsStillRunning = true; break; } } if (!threadsStillRunning) allThreadsDone = true; } protected override OnFormClosing(FormClosingEventArgs e) { if (!allThreadsDone) { e.Cancel = true; MessageaBox.Show("Threads still running!"); } }
如果任何线程仍在运行,这应该可以防止表单关闭.