Win32 threads vs. Thread gotcha (and a little GC surprise)....
During a recent code review, the following piece of C# code set off a red flag:
void CreateAThread()
{
Thread NewThread = new Thread(...);
...//Assign ThreadStart etc...
NewThread.Start(); //Long live the thread...
}
The intention here is to create a new thread that will live till the process terminates. Come to think of it, such code would make perfect sense to someone who comes from a C++ background.
For example, consider the following C++ code:
void CreateAThread()
{
HANDLE ThreadHandle = CreateThreadEx(.....); //Call Win32 API to create a thread....
CloseHandle(ThreadHandle);
}
In the C++ case, the thread continues to run after return from the function.
However, in the managed world, Thread is just another object and therefore NewThread is a reference that a prime candidate for GC. So, what happens when the GC collects a Thread() object? My guess was that the actual OS thread would be terminated by the Finalizer().
To confirm my suspicion, I stepped into the code with a debugger and called GC.Collect() after exiting from CreateAThread(). Interestingly enough, the thread continued to run even after GC.Collect()!!! Is this because the GC has some buit in checks for such special type of objects? In any case, I think that it's bad practice to rely upon GC behaviour and it's imperative to assign the Thread reference alive for the lifetime of the thread. What do you folks think? Atul