你能僵局调用所以GC.Collect和GC.WaitForPendingFinalizers?你能、僵局、GC、Collect

2023-09-03 16:30:46 作者:月老肯定玩断了我的红绳

考虑以下内容:

  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()
    {
        锁(本)
        {
            // ...
        }
    }
}
 

arcgis api for js调用本地发布的服务报错,调用别人的可以成功

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)
        {
            // ...
        }
    }
}