开发者

Will outer object be GCed if a class member is KeepAlived in C#?

开发者 https://www.devze.com 2023-02-12 02:28 出处:网络
see this class: class Outer { private Foo _foo; public Outer() { _foo = new Foo(); GC.K开发者_如何学编程eepAlive(_foo);

see this class:

class Outer
{
    private Foo _foo;

    public Outer()
    {
        _foo = new Foo();
        GC.K开发者_如何学编程eepAlive(_foo);
    }
}

If I create an object of class Outer, will the object be GCed?


Are you sure that you've correctly understood how KeepAlive works?

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.

So you're instantiating an instance of Outer. The constructor instantiates _foo and immediately calls KeepAlive. That KeepAlive call ensures that _foo is not collected in the time between when it was instantiated and when KeepAlive was called. As soon as the KeepAlive call has completed, _foo is eligible for collection.

The instance of Outer -- or any other class -- is eligible for collection as soon as it is no longer in use. Even theoretically, the call to KeepAlive is irrelevant: it might keep _foo alive for slightly longer, but it makes no difference to the outer class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号