What prevents a Thread in C# from being Collected?

2019-01-15 13:04发布

问题:

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).

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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?



回答5:

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



回答6:

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.