本文介绍了垃圾收集和终结:细点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在回答记者有关SO另一个问题,以及随后的评论的讨论中,我遇到了对我不是明确点墙壁上。 在纠正我,在那里我误入歧途... 的任何一点在垃圾收集器收集的对象,它会调用该对象的终结,在一个单独的线程(除非终结一直被压制,例如通过的Dispose()方法)。虽然收集,GC的暂停只是触发采集(采集背景除外)的线程的所有线程 什么是不明确的: 是否垃圾收集器收集么? 如果不是之前等待终结该对象上执行,不是取消暂停线程而终结仍在执行? 如果它不等待,如果终结跑进正在举行由挂起线程上的锁,会发生什么?是否终结线程死锁? (在我的答案,我认为这是糟糕的设计,但我可能看到的情况下会发生这种情况) TIA, 詹姆斯 链接到原来的问题: 的。NET的GC终结访问同步对象。 解决方案 Your question is a bit ambiguous.When the GC encounters a "dead" object that needs finalization, it abandons its attempt to reclaim the dead object's storage. Instead, it puts the object on a queue of "objects that I know need finalization" and treats that object as alive until the finalizer thread is done with it.So, yes, the GC does "wait" until the finalizer is executed before reclaiming the storage. But it does not wait synchronously. It sounds like you're asking "does the GC synchronously call the finalizer right there?" No, it queues up the object to be finalized later and keeps on truckin'. The GC wants to quickly get through the task of releasing garbage and compacting memory so that the program proper can resume running ASAP. It's not going to stop to deal with some whiny object that is demanding attention before it gets cleaned up. It puts that object on a queue and says "be quiet and the finalizer thread will deal with you later."Later on the GC will check the object again and say "are you still dead? And has your finalizer run?" If the answer is "yes" then the object gets reclaimed. (Remember, a finalizer might make a dead object back into a live one; try to never do that. Nothing pleasant happens as a result.)I believe that the GC thaws out the threads that it froze, and signals the finalizer thread "hey, you've got work to do". So when the finalizer thread starts running, the threads that were frozen by the GC are starting up again.There might have to be unfrozen threads because the finalizer might require a call to be marshalled to a user thread in order to release a thread-affinitized resource. Of course some of those user threads might be blocked or frozen; threads can always be blocked by something.You betcha. There's nothing magic about the finalizer thread that prevents it from deadlocking. If a user thread is waiting on a lock taken out by the finalizer thread, and the finalizer thread is waiting on a lock taken out by the user thread, then you've got a deadlock.Examples of finalizer thread deadlocks abound. Here's a good article on one such scenario, with a bunch of links to other scenarios:http://blogs.microsoft.co.il/blogs/sasha/archive/2010/06/30/sta-objects-and-the-finalizer-thread-tale-of-a-deadlock.aspxAs the article states: finalizers are an extremely complex and dangerous cleanup mechanism and you should avoid them if you possibly can. It is incredibly easy to get a finalizer wrong and very hard to get it right. 这篇关于垃圾收集和终结:细点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 22:35