What prevents a Thread in C# from being Collected? What prevents a Thread in C# from being Collected? multithreading multithreading

What prevents a Thread in C# from being Collected?


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.