How to determine if child threads have completed

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.

+5
source share
6 answers

You can use Process.GetCurrentProcess (). Threads.Count.

+1
source

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(), , .

, , / .

+5

, , , - , ( , ). Interlock.Decrement - ( -ve, , , ), ManualResetEvent Monitor.Pulse; . .

, TPL 4.0, ( , Parallel.For PLINQ).

, () , ? , - :

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

, , .

+1

Thread.Join(). 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...///
0

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.

0
source

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();
0
source

All Articles