如何判断对象是否已被垃圾回收 [英] How to Tell If an Object Has Been Garbage Collected

查看:144
本文介绍了如何判断对象是否已被垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么知道该对象是否已被垃圾回收?

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

推荐答案

根据

通常无法通过使用对该对象的引用来判断该对象是否已被垃圾回收-因为一旦引用了该对象,它就会赢

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.

您可以改为使用WeakReference对象创建对对象的弱引用。出于垃圾收集的目的,弱引用是不会被视为引用的一个引用。

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);

这篇关于如何判断对象是否已被垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆