views:

173

answers:

2

Let's say I create an object, and that object starts a thread, and gives one of its private instance methods to ThreadStart. Later, all references to that object are gone. What happens? Is the object is never garbage collected because the thread holds a reference to it through the this pointer? On the other hand, if I use a static method, how can the thread detect that its object was garbage collected and end?

I know I shouldn't normally make threads lifetime dependent on garbage collection. I don't want my object to leak when it's not disposed correctly.

+3  A: 

Creating a thread does not hold a direct reference to the object, other than any references indirectly held via the delegate. The thread uses the ThreadStart to begin running, but it does not hold a reference other than the delegate being run.

If the method is an instance method, the object will not be garbage collected until the thread method completes. The delegate requires the reference to the object instance, and keeps it rooted. When the thread delegate completes, the object in question becomes unrooted, and is elegible for garbage collection.

If it's a static method, this is not an issue. There is no reference to the instance - only to the type. The instance that started the thread will not be referenced by the newly created thread - so it will run until the completion of it's method, and then shutdown. Garbage collection of the instance is handled the same as if the thread did not exist (ie: when the other references go away, the object will be available for GC).

Reed Copsey
And I can pass a `WeakReference` to `this` to the thread running a static method to allow the object be garbage collected *and* let the thread know when that happens.
CannibalSmith
Well, a WeakReference doesn't do any form of notification - but it would allow a static method to poll the reference and see when/if it gets collected.
Reed Copsey
A: 

If you store a delegate to an instance method somewhere (e.g. by giving it to the thread), the delegate will contain a reference to the object, which will be stored somewhere in the TreadObject, so the object will not be garbage collected until the thread has ended.

If you give ThreadStart a static method the delegate will not contain any references to instances, so the garbage collector will not be hindered by the existance of the thread (when it comes to the object in question at least).

Grizzly