本文介绍了你能僵局调用所以GC.Collect和GC.WaitForPendingFinalizers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下内容:
GC.Collect的(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
所以GC.Collect(GC.MaxGeneration);
考虑到多线程和垃圾收集方式,在什么情况下,你会得到 WaitForPendingFinalizers
死锁?
注:我不是在寻找的,为什么你不应该叫 GC.Collect的
解决方案
//导致死锁时发布配置构建并没有调试器附着
//建筑在调试模式和/或附加调试器可能会继续
// badIdea存活更长的时间,在这种情况下,你不会看到僵局
//除非你明确地设置badIdea调用Monitor.Enter后空
VAR badIdea =新BadIdea();
Monitor.Enter(badIdea);
所以GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
所以GC.Collect(GC.MaxGeneration);
// ...
公共类BadIdea
{
〜BadIdea()
{
锁(本)
{
// ...
}
}
}
Given the following:
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration);
Taking into account multi-threading and Garbage Collection modes, under what circumstances would you get a deadlock on WaitForPendingFinalizers
?
Note: I am not looking for answers about the reasons why you shouldn't be calling GC.Collect
.
解决方案
// causes a deadlock when built with release config and no debugger attached
// building in debug mode and/or attaching the debugger might keep
// badIdea alive for longer, in which case you won't see the deadlock
// unless you explicitly set badIdea to null after calling Monitor.Enter
var badIdea = new BadIdea();
Monitor.Enter(badIdea);
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration);
// ...
public class BadIdea
{
~BadIdea()
{
lock (this)
{
// ...
}
}
}
这篇关于你能僵局调用所以GC.Collect和GC.WaitForPendingFinalizers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!