views:

392

answers:

4

I've just read up on Thread.IsBackground and if I understand it correctly, when it's set to false the Thread is a foreground thread which means it should stay alive until it has finished working even though the app have been exited out. Now I tested this with a winform app and it works as expected but when used with a console app the process doesn't stay alive but exits right away. Does the Thread.IsBackground behave differently from a console app than a winform app?

+1  A: 

I believe with the winforms based app you get a seperate thread to handle the messaging, so if the "main" thread exits, you still have a thread going to keep the process alive. With a console app, once main exits, unless you started a foreground thread, the process also terminates.

John Gardner
The process seems to terminate even though I've started a foreground thread.
John
A: 

Someone please tag this .NET. In Java, you would mark your thread non-daemon by Thread.setDaemon(false) .

wbkang
A: 

IMHO really you should be a lot more explicit about the expected semantics of your application and deliberately <thread>.Join.

stephbu
+2  A: 

The Thread.IsBackground property only marks if the thread should block the process from exiting. It doesn't perform any magic to keep the thread alive until some sort of explicit exit.

To quote the Thread.IsBackground Property MSDN (emphasis mine):

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

In order to keep your console app alive you'll need to have some sort of loop which will spin until you ask it to stop via a flag or similar. Windows Forms applications have this built in because of their message pump (I believe).

Aydsman