Make sure all threads are complete.

In the win form application, I have an array of threads that start as follows:

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 } 

Now, if the user presses STOP, the boolean for stop will be set to true, so the threads will exit the Job method one by one. How can I make sure all threads are complete?

NOTE. I need traditional streaming for my case, and TaskLibrary does not fit my scenario.

+6
source share
3 answers

Have you thought about using BackgroundWorkers instead? You said "traditional flows." I'm not quite sure what you mean, so I don’t know if this is a valid offer or not, but here it is anyway if Join() does not solve your problem.

 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!"); } } 

This should prevent the form from closing if any threads are still running.

+4
source

Use the Join method to check if all threads have stopped.

  foreach (var t in threads) { t.Join(); } 
+7
source

I'm not sure if this is what you are looking for, but here is a simple solution that I used in .NET 3.0 to make sure that a large but deterministic number of threads completed before proceeding:

Global:

 AutoResetEvent threadPoolComplete = new AutoResetEvent(false); static int numThreadsToRun; 

When activating threads:

 numThreadsToRun = [number of threads]; [start your threads]; threadPoolComplete.WaitOne(); 

At the end of each stream code:

 if (Interlocked.Decrement(ref numThreadsToRun) == 0) { threadPoolComplete.Set(); } 
+1
source

Source: https://habr.com/ru/post/890108/


All Articles