.net - 如果类成员在C#中KeepAlived,外部对象是否会被GC?

标签 .net garbage-collection

查看此类:

class Outer
{
    private Foo _foo;

    public Outer()
    {
        _foo = new Foo();
        GC.KeepAlive(_foo);
    }
}

如果我创建一个 Outer 类的对象,该对象会被 GC 吗?

最佳答案

您确定您已正确理解 KeepAlive有效吗?

References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.

因此,您正在实例化 Outer 的实例。构造函数实例化 _foo 并立即调用 KeepAlive。该 KeepAlive 调用可确保 _foo 在实例化和调用 KeepAlive 之间的时间内不会被收集。一旦 KeepAlive 调用完成,_foo 就符合收集条件。

Outer 的实例(或任何其他类)一旦不再使用,就可以被收集。即使从理论上讲,对 KeepAlive 的调用也是无关紧要的:它可能会使 _foo 保持存活稍微的时间,但这对外部类没有任何影响。

关于.net - 如果类成员在C#中KeepAlived,外部对象是否会被GC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5024680/

相关文章:

.net - 使用 log4Net 在单个进程中记录多个客户端的帮助

c# - 通过 lambda 使对象保持事件状态

c++ - 引用计数垃圾收集

DOM 事件监听器垃圾回收

.net - 用于月亮和太阳落下/升起时间的 Web 服务或 .net 库?

.net - 在 .Net 中, "most terse"检查字符串是否为多个值之一的方法?

c# - COM/.NET 互操作程序集能否与较新版本的 COM 组件一起使用?

c# - Entity Framework : Eager Loading Navigation Properties of Inherited Entities

c# - 垃圾收集和 GCHandle.Alloc

python-3.x - 创建实例失败时调用的析构函数?