视图模型是否由垃圾收集器收集?我怎么查?

Is the view model collected by garbage collector? How could I check?

我有这样的代码:

public class ViewModel01
{
    public ObservableCollection<MyType> MyProperty;
}

Public class ViewModel02
{
    ObservableCollection<MyType> MyProperty;


    Public ViewModel02()
    {
        ViewModel01 myViewModel = new ViewModel01;
        MyProperty = myViewModel01.MyProperty;
    }
}

我的疑问是,如果在第二个视图模型的构造函数中,对象 myViewModel 被垃圾收集器重新收集,或者它仍然保持活动状态,同时 ViewModel02 仍然存在,因为我引用了视图的 属性模型 01。或者也许视图模型 01 被收集是因为我确实引用了 ObservableCollection,而不是视图模型 01,所以视图模型可以被垃圾收集器收集。

另外,我想知道是否有一些方法可以检查一个对象是否被收集。我正在使用 visual studio 2019 社区。

谢谢。

如果您真的想知道您是否在泄漏某个对象,您可以尝试手动跟踪活动计数;像下面这样简单的东西通常有效:

class Foo
{
    static int s_liveCount;
    Foo() => Interlocked.Increment(ref s_liveCount);
    ~Foo() => Interlocked.Decrement(ref s_liveCount);
    public static int LiveCount => Thread.VolatileRead(ref s_liveCount);
}

不过,这仅告诉您整个类型;跟踪单个对象更加混乱,因为在你尝试的那一刻 - 你有点停止收集它,除非你通过 WeakReference

是的,myViewModel01 应该被 GC 收集,因为没有引用它。未收集 Observable 集合,因为 ViewModel02 持有对它的引用。

你可以这样测试:

public class ViewModel01
{
    private readonly Guid _id;

    public ViewModel01()
    {
        _id = Guid.NewGuid();
        Console.WriteLine($"Constructing {_id}");
    }

    ~ViewModel01()
    {
        Console.WriteLine($"Destructing {_id}");
    }

    public ObservableCollection<MyType> MyProperty;
}

static void Main(string[] args)
{
    var model102 = new ViewModel02();
    GC.Collect(); // Force GC to collect garbage
    Console.ReadKey();
}

您将在输出中看到 ViewModel01 已构建然后被销毁。