0

say my main thread calls a loop which makes new threads and starts them on some other function.

for (int i = 0; i < numberOfThreads; i++)
{
        Thread thread = new Thread(start);
        thread.Start();
}
call_This_Function_After_All_Threads_Have_Completed_Execution();

How can i ensure that my method gets called only after all the other threads have completed execution.

Win Coder
  • 6,628
  • 11
  • 54
  • 81
  • 5
    [`Task`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx) will make your life lot easier. :) – Leri Oct 12 '13 at 13:12
  • Take a look at this post: http://stackoverflow.com/questions/1584062/how-to-wait-for-thread-to-finish-with-net – JohnLBevan Oct 12 '13 at 13:19

1 Answers1

1

You can use AutoResetEvent-s. Declare an AutoResetEvent array where all the threads can reach it.

AutoResetEvent[] events = new AutoResetEvent[numberOfThreads];

Start threads like this:

for (int i = 0; i < numberOfThreads; i++)
{
    events[i] = new AutoResetEvent(false);
    Thread thread = new Thread(start);
    thread.Start(i);
}
WaitHandle.WaitAll(events);
call_This_Function_After_All_Threads_Have_Completed_Execution();

And finally don't forget to call the Set() method in the threads:

 void start(object i)
 {
       //... do work
       events[(int) i].Set();
 }
toderik
  • 479
  • 4
  • 8