The thread class is simply a wrapper around an Operating system thread object. Not it doesn't implement IDisposable, this is because the OS handles the termination and cleanup of the OS thread object when it receives notification that a process has terminated.
The corresponding operating system thread continues to execute even if the Thread object is collected. If the thread is set to background, however, and the application terminates, the thread that was set to background will also terminate along with the process. If the thread is not a background thread, the OS will allow the process to continue running until the thread terminates.
Take the following small program for example:
static void Main( string[] args )
{
Thread t = new Thread(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Hi");
Console.ReadLine();
});
t.IsBackground = true;
t.Start();
}
This thread never finishes executing before the process terminates, and the background thread with it. Comment out that line, and the application will wait until the thread completes to terminate the application.
That being said, you can't be sure when the Thread object is collected. There's nothing in this application indicating that the Thread object will be collected immediately. It might be out fo scope, but that doesn't mean it's collected. It first has to go through the same garbage collection algorithm as everything else. Out of scope doesn't necessarily mean collected.
But to answer your question, IsBackground has no effect on whether or not something is garbage collected, or when it is. It's completely independent of that.
To simplify:
The OS thread doesn't terminate just because the Thread object is collected.
The thread will continue to execute until it terminates if IsBackground is set to false. If IsBackground is set to true, and all the foreground threads in the application terminate, the thread in question will be brought down along with the last foreground thread, unless it completes before all foreground threads are terminated, in which case, it will execute to completion.
Coding Light - Illuminated Ideas and Algorithms in SoftwareCoding Light Wiki �
LinkedIn �
ForumsBrowser