gpt4 book ai didi

c# - ASP.NET:在某些情况下我应该担心内存泄漏吗? [C#]

转载 作者:行者123 更新时间:2023-11-30 13:34:03 24 4
gpt4 key购买 nike

我担心两个对象相互引用时的垃圾收集问题......

public class A
{ public readonly B _b;
public A()
{ _b = new B(this);
}
}

public class B
{ public readonly A _a;
public B(A objA)
{ _a = objA;
}
}

在这种情况下,第三个类可能引用 A ...

public class Foo
{ public A _a = new A(); // A and B are both created here.
public void Bar()
{ _a = new A();
} // Create a new A (and B)
}

通常,垃圾收集器会处理不再具有任何事件引用的对象。但在这种情况下,A 和 B 对象永远不会丢失它们所有的事件引用,因为它们总是相互引用。

Foo 对象用新的 A(和 B),垃圾收集器是否能够在不启动循环对象引用的无限循环的情况下清理旧的 A(和 B)?

这是一个严重的问题,因为它是一个 ASP.NET 应用程序。这些对象将在每个网络请求中创建多次,如果垃圾收集器无法清理它们,它们可能会一直存在,直到服务器重新启动。
可能的负面结果:
<< 网络服务器因 RAM 溢出而崩溃。
<< Web 服务器因无限垃圾收集循环而崩溃。

.NET 如何处理此类场景中的垃圾收集?

最佳答案

.NET GC 通过跟踪根引用来工作,例如静态字段和作用域内局部变量。它正确处理引用循环。例如如果 A <--> B,但两者均未从根引用中引用,则将其收集。

Let's consider how the GC determines when it can reclaim memory. When the CLR attempts to allocate memory and has insufficient memory in reserve, it performs a garbage collection. The GC enumerates all rooted references, including static fields and in-scope local variables on any thread's call stack. It marks these references as reachable and follows any references these objects contain, marking them as reachable as well. It continues this process until it has visited all reachable references. Any unmarked objects are not reachable and hence are garbage. The GC compacts the managed heap, tidies up references to point to their new location in the heap, and returns control to the CLR. If sufficient memory has been freed, the allocation proceeds using this freed memory. If not, additional memory is requested from the operating system.

-- 来自 http://msdn.microsoft.com/en-us/magazine/cc163491.aspx

关于c# - ASP.NET:在某些情况下我应该担心内存泄漏吗? [C#],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4433503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com