鉴于以下情况:
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration);
考虑到多线程和垃圾收集模式,在什么情况下您会在 WaitForPendingFinalizers
上发生死锁?
注意:我不是在寻找您不应该调用 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)
{
// ...
}
}
}
关于c# - 您可以在调用 GC.Collect 和 GC.WaitForPendingFinalizers 时出现死锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386585/