How to Tell If an Object Has Been Garbage Collecte

2020-03-01 07:42发布

How I can know to tell if an Object has been garbage collected or not?

1条回答
Lonely孤独者°
2楼-- · 2020-03-01 08:13

According to this:

You normally can’t tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won’t be garbage collected.

You can instead create a weak reference to an object using the WeakReference object. The weak reference is one that won’t be counted as a reference, for purposes of garbage collection.

In the code below, we check before and after garbage collection to show that a Dog object is garbage collected.

        Dog dog = new Dog("Bowser");

        WeakReference dogRef = new WeakReference(dog);
        Console.WriteLine(dogRef.IsAlive);

        dog = null;
        GC.Collect();

        Console.WriteLine(dogRef.IsAlive);

enter image description here

查看更多
登录 后发表回答