views:

865

answers:

6

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 .Net framework, I just don't have it handy).

A: 

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?

Jon
A: 

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.

Grad van Horck
No, it wont. The runtime keeps a reference. Otherwise a running thread would be collected if you loose the reference.
EricSchaefer
+2  A: 

The runtime keeps a reference to the thread as long as ist ist running. The GC wont collect it as long as anyone still keeps that reference.

EricSchaefer
That's what I thought. Do you know the exact mechanism (just out of curiosity)?
ripper234
+1  A: 

It's a hard-wired feature of garbage collector. Running threads are not collected.

ima
A: 

Important point to note though - if your thread is marked with IsBackground=True, it won't prevent the whole process from exiting

Damien_The_Unbeliever
A: 

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.

Ilya Ryzhenkov