I have the following multithreaded program:
class Program{
static void main(){
(new Thread(DoSomething)).Start();
}
static void DoSomething(){
// Dome something here...
}
}
A couple of questions:
- Does the main thread exit after spinning off the child thread?
- If it does exit and the child thread is a background thread: Is the main process going to exit or will it wait for the background thread to finish?
Typically, if you want to wait for the child thread to complete, you’d add a
x.Join();line (where x is the variable of your thread) wherever you want your main thread to stop and wait for the child to complete.EDIT: So, yes, the main thread will exit unless one of three cases occurs:
a) the spawned thread completes before the rest of the main thread code (if you add any)
b) You have a condition that waits for the thread to complete (such as the Join statement I mentioned, but there are other ways too).
c) The main thread goes into a semi-infinite loop (such as a game/graphics engine).
In your bare-bones example, it will exit for sure (given your question’s parameters, a background thread).
EDIT2: Sorry, I seem to have dodged your second question (and actually only considered background threads the whole while). If it’s a background thread it will exit as I’ve explained, if it’s foreground then it shouldn’t (though I don’t have much experience with foreground threads, so I can’t say for sure).
So to answer your questions: Yes, the main thread exits. Yes, if the child is specifically a background thread, the process will exit as well.
EDIT3: Final edit, I promise. I just wanted to add some code so that you could prove the answer yourself (which is always nice to be able to do):
By toggling the
thready.IsBackground = true;tothready.IsBackground = false;you get a program that runs forever (not exiting until the thread does). Leaving it as true will exit very quickly.