In .NET, after this code, what mechanism stops the Thread
object from being garbage collected?
new Thread(Foo).Start();
GC.Collect();
Yes, it's safe to assume something has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me System.Threading
, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).
The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference.
It depends on whether the thread is running or not. If you just created Thread object and didn't start it, it is an ordinary managed object, i.e. eligible for GC. As soon as you start thread, or when you obtain Thread object for already running thread (GetCurrentThread) it is a bit different. The "exposed object", managed Thread, is now hold on strong reference within CLR, so you always get the same instance. When thread terminates, this strong reference is released, and the managed object will be collected as soon as you don't have any other references to (now dead) Thread.
It's a hard-wired feature of garbage collector. Running threads are not collected.
Well, it's safe to assume that if a thread is running somewhere that something has a reference to it so wouldn't that be enough to stop the garbage collection?
Important point to note though - if your thread is marked with IsBackground=True, it won't prevent the whole process from exiting
Assign the new Thread to a local field?
class YourClass
{
Thread thread;
void Start()
{
thread = new Thread(Foo);
thread.Start();
GC.Collect();
}
}
Garbage Collection collects everyting that is not references, so in your code there is no field/variable referencing to the thread, so it will be collected.