Threading - IsBackground
During my System.Threading talk last night one of the questions from the audience asked what the IsBackground property on the Thread classes was used for.
The intellisense for this property says "Gets or Sets a value indicating whether or not the tread is a background thread." which to be honest I think we could have guessed! What this description lacks is any information about why you would want to set it.
It's always embarrassing when you can't immediately answer a question from the audience but in this case I was stumped so I promised to investigate the answer and here it is.
The IsBackground property allows you to tell the runtime if the thread is a foreground (UI) thread or a background thread. By default all threads are created as foreground threads unless you change this property.
So why do we care?
Well, the .NET runtime does something special when the last foreground thread terminates - it aborts all the background threads and terminates the application. (We know Thread.Abort is bad however if the application is being shutdown anyway that badness has a very limited duration.)
This can be nicely illustrated by creating a WinForms application which launches a background thread which runs forever. By default when you run your application it will run forever unless you explicitly abort the background thread or the application. This can be seen by running your simple application, closing the Form1 window and noticing the application is still running.
If however you set IsBackground to true after creating your background thread:
Thread t = new Thread(new ThreadStart(BackgroundThread));
t.IsBackground = true;
t.Start();
You will notice that when you close the only window (Form1) the application will terminate.
I will certainly be updating our System.Threading presentation to explain this behaviour more clearly in the future. A great question and something we should all be doing.