Click here to Skip to main content
15,877,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I wait for a thread to complete and then exicute remaining code.

C#
class2 objClass2 = new class2();// (In Class2 cunstructor I have thread)
class3  objclass3  = new class3();//This line should execute only after the execution of Class2 thread


Please help
Posted
Updated 3-Jan-12 1:34am
v2

I think you should not have threads in your constructor. You should consider re-factoring your code design.

However to solve your problem one thing you can do is -

Use ManualResetEvents.

So your code would look something like this -

private static ManualResetEvent mre = new ManualResetEvent(false);

/* Somehow you need to make mre accessible to the piece of code which can decide that the Thread 1 has finished its execution. There you would do a mre.Reset() */

mre.Set();
class2 objClass2 = new class2(mre);// (In Class2 cunstructor I have thread)

mre.WaitOne();
class3  objclass3  = new class3();//This line should execute only after the execution of Class2 thread



Thanks,
Pankaj Chamria
 
Share this answer
 
First you should think of removing the extra thread in the constructor of class2.

If that's not possible, have a look at the Thread.Join()[^] method. It is designed to make one thread to wait for another one to exit. Use it in the constructor of class2.
 
Share this answer
 
v2
Comments
BobJanova 3-Jan-12 8:53am    
Exactly right. Thread.Join will do what the question asks, but this definitely looks like a bad piece of design.
You can also look at initiating Class3 at the end of the thread of Class2, if that is not possible you can also look at thread locking and using the Mutex object.

lock Statement[^]

Look at example 4 for the use of the Mutex object.
Mutex object[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900