开发者

How do garbage collection and background threads interact in .NET?

开发者 https://www.devze.com 2022-12-17 12:25 出处:网络
Let\'s say I create an object, and t开发者_JAVA百科hat object starts a thread, and gives one of its private instance methods to ThreadStart. Later, all references to that object are gone. What happens

Let's say I create an object, and t开发者_JAVA百科hat 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消