When all threads are completed

This is my first real attempt to use multithreading, I want to know how I can tell when all my task groups are executed:

for (int i = 0; i < taskGroups.Count(); i++) {
    ThreadStart t = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
if(allThreadsComplete){ //???

}

Any help would be greatly appreciated

Application:

ThreadStart[] threads = new ThreadStart[taskGroups.Count()];
for (int i = 0; i < taskGroups.Count(); i++) {
    threads[i] = new ThreadStart[]
    threads[i] = delegate { RunThread(taskGroups[i]); };
    new Thread(t).Start();
}
bool threadsComplete = false;
while(!threadsComplete){
    for(int i=0;i<taskGroups.Count();i++){
        if(threads[i].State == complete)
        threadsComplete = true;
    }
}
+3
source share
6 answers

You need to save all your threads and then call Thread.Join ().

Something like that:

List<Thread> threads = new List<Thread>();
for (int i = 0; i < taskGroups.Count(); i++) {
   int temp = i; //This fixes the issue with i being shared
   Thread thread = new Thread(() => RunThread(taskGroups[temp]));
   threads.Add(thread);
   thread.Start();
}

foreach (var thread in threads) {
    thread.Join();
}
+4
source

If you are using 3.5, you can write your own CountdownEvent, if you are using 4.0, you can use the built-in CountdownEvent to do something like this:

CountdownEvent = new CountdownEvent(taskGroups.Count());

for (int i = 0; i < taskGroups.Count(); i++) 
{
    int item = i; // copy i locally
    ThreadStart t = delegate 
    { 
        RunThread(taskGroups[item]); 
        latch.Signal();
    };
    new Thread(t).Start();
}

latch.Wait();

latch.Wait()will block your code until the threads run out. Also, you might want to change the way you start the stream:

CountdownEvent = new CountdownEvent(taskGroups.Count());

for (int i = 0; i < taskGroups.Count(); i++) 
{
    int item = i; // copy i locally
    Thread t = new Thread(()=>
    { 
        RunThread(taskGroups[item]); 
        latch.Signal();
    });
    t.IsBackground = true;
    t.Start();
}

latch.Wait();

, : (.. ).

+1

ThreadState Thread.

0
0

, , , ( ), taskGroups.Count().

0

Task.

In any case, if you want to wait for all your threads, you can call Thread.Join:

var threads = new List<Thread>();    
for (int i = 0; i < taskGroups.Count(); i++) {
    ThreadStart t = delegate { RunThread(taskGroups[i]); };
    var thread = new Thread(t);
    threads.Add(thread);
    thread.Start();
}

threads.ForEach(a => a.Join());

Remember that you can also pass a timeout parameter that will wait for the end of the stream only if it does not take more time during which you passed.

0
source

All Articles