I use multiple threads in my application using a while (true) loop, and now I want to exit the loop when all active threads complete their work.
You can use Process.GetCurrentProcess (). Threads.Count.
Assuming you have a list of the threads themselves, here are two approaches.
Solution one:
Use Thread.Join () with the timespan parameter to synchronize with each thread in turn. The return value tells you whether the thread is complete or not.
Solution two:
Thread.IsAlive(), , .
, , / .
, , , - , ( , ). Interlock.Decrement - ( -ve, , , ), ManualResetEvent Monitor.Pulse; . .
Interlock.Decrement
ManualResetEvent
Monitor.Pulse
, TPL 4.0, ( , Parallel.For PLINQ).
Parallel.For
, () , ? , - :
T workItem; while(queue.TryDequeue(out workItem)) { // this may block until either something ProcessWorkItem(workItem); // todo, or the queue is terminated } // queue has closed - exit the thread
, , .
Thread.Join(). Join , (, Join).
Thread.Join()
Join
, , Join . , . - :
for(int i = 0 ;i < childThreadList.Count; i++) { childThreadList[i].Join(); } ///...The following code will execute when all threads in the list have been terminated...///
I believe using Join () is the cleanest way. I often use multiple threads, and each thread usually loads data from different data sources (Informix, Oracle, and SQL at the same time.) A simple loop, as mentioned above, calls Join () on each stream object (which I store in a simple List object) works !!!
Carlos Merich.
I prefer to use HashSet streams:
// create a HashSet of heavy tasks (threads) to run HashSet<Thread> Threadlist = new HashSet<Thread>(); Threadlist.Add(new Thread(() => SomeHeavyTask1())); Threadlist.Add(new Thread(() => SomeHeavyTask2())); Threadlist.Add(new Thread(() => SomeHeavyTask3())); // start the threads foreach (Thread T in Threadlist) T.Start(); // these will execute sequential NotSoHeavyTask1(); NotSoHeavyTask2(); NotSoHeavyTask3(); // loop through tasks to see if they are still active, and join them to main thread foreach (Thread T in Threadlist) if (T.ThreadState == ThreadState.Running) T.Join(); // finally this code will execute MoreTasksToDo();