垃圾收集弱引用与结构引用

Garbage collecting a weak reference vs a struct reference

我正在做一些练习题,其中一个如下:

You are creating a class named Data that includes a dictionary object named _data. You need to allow the garbage collection process to collect the references of the _data object. How should you complete the relevant code?

public class Data
{
    <replace1>
    public Data(int count)
    {
        for (int i = 0; i < count; i++)
        {
            <replace2>
        }
    }
}

选项如下:

static Dictionary<int, WeakReference> _data;
static Dictionary<int, Int32> _data;
_data.Add(i, new WeakReference(new Class(i*2), false));
_data.Add(i, (Int32)(i*2));

因为,基本上,问题是 "Should you use a WeakReference or a struct reference if you want the Garbage Collector to be able to collect your objects?" 我认为 Int32 结构是更好的选择,因为它不引用堆上的任何对象,因此可以立即对对象进行垃圾回收,尽管如果没有对对象的强引用(据我了解),弱引用不会使对象保持活动状态,但我仍然认为结构将是一个更好的答案 但实践测试表明 WeakReference 是正确答案。请注意,即使对于最明显和最简单的问题,此练习测试也曾出错。

你能解释一下为什么在这种情况下,如果我们希望 GC 能够收集我们的对象,WeakReference 比结构更适合吗?

要使 GC 能够收集您必须使用 Wea​​kReference 的对象,因为它不持有对您的对象的强引用。 参见:https://docs.microsoft.com/de-de/dotnet/api/system.weakreference

在你的情况下,结构将被放置在堆上,因为你将它存储在一个显然存储在堆上的字典中。因此,将创建一个强引用,并且在您将其从字典中删除之前不会收集您的结构。

当您想要缓存大型对象但不需要它们始终可访问时,您通常会使用 Wea​​kReference。所以当你的程序需要在别处存储时,WeakReference 允许 GC 收集对象。