Reputation: 129
I ran into an issue where the application closes even though threads are running in the background when a while( true ) loop is not running on it's own(without a thread) in the main method.
Pseudo example:
public static void Method1() {
while( true ) {}
}
public static void Method2() {
while( true ) {}
}
public static void main() {
Thread myThread1 = new Thread( () => Method1() );
Thread myThread2 = new Thread( () => Method2() );
myThread1.Start();
myThread2.Start();
}
Now when that program runs, it stops execution after starting the threads, even though the threads are running infinite while loops. How do I void this? I know I can add an infinite loop in the main method, but that seems odd.
Someone recommended I use a mutex or semaphone, however I don't now where to start with those or how to apply them to my application.
Upvotes: 0
Views: 49
Reputation: 8551
I think all you should need is to set the threads' IsBackground property to false:
http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground%28v=vs.110%29.aspx
Upvotes: 4
Reputation: 103437
When the main thread exits, the app exits. That's normal.
You can just use Thread.Join
to wait for them both to terminate.
myThread1.Start();
myThread2.Start();
myThread1.Join();
myThread2.Join();
Edit: actually, @adv12's answer is better: set the threads to be foreground threads so that the app won't terminate until they finish.
Upvotes: 1
Reputation: 3555
Yes you can use a mutex, see the MSDN documentation
In the class
private static Mutex mut = new Mutex();
And in your methods use
mut.WaitOne();
mut.ReleaseMutex();
The main will exit but the threads will run until the mutex is released
Upvotes: 0