0

我有一个多播委托字典,其中键是特定的消息类型,值是多播委托,即消息处理程序。

当我想清除该字典时,我想确保所有代表都未绑定和取消引用并最终被垃圾收集 - 清除字典是否足够,或者我应该枚举值(多播代表)并在清除之前先将它们设置为 null查字典?

4

3 回答 3

1

Unless you have a counter example (in which case you should open a bug report with MS) garbage collection in .NET should not be a concern. It's fairly sophisticated, and can track down objects that aren't referenced in code, even if they are part of an arbitrarily large object graph that is un-referenced from the running image.

Even so, there isn't a difference between clearing the dictionary and setting all its values to null. Both have the same effect of simply dereferencing the underlying values. This is overkill.

The real concern with .NET isn't reference-safety, but resource leaking: any IDisposable class should be disposed before dereferencing it. However, MulticastDelegate is not a disposable class, so this is moot.

In other words: this is .NET, not C. Stress less. No worries.

于 2017-01-17T12:58:18.550 回答
0

System.Delegate(和 System.MulticastDelegate)类的处理方式与任何其他类相同,它们只是恰好包含指向函数和目标对象的指针。因此,出于所有意图和目的,您可以将其视为对目标对象的引用。

如果您完成了它们,只需清除字典,如果您完成了包含对象,您甚至不需要这样做。将它们单独设置为 null 不会做任何清除字典不会做的事情。

一旦任何对象不再可访问,它就有资格进行垃圾收集,如果您不熟悉垃圾收集机制,那么我强烈建议您阅读一下这个主题。

于 2017-01-17T13:14:34.493 回答
-1

只需将它们设置为空。

foreach (var d in dict)
{
    d = null;
}

当编译器不再对这些有任何引用时,它会为你收集垃圾。

最终,只需将整个 dict 设为 null:

dict = null;

C# 中的垃圾收集应该不是问题。

于 2017-01-17T12:54:43.160 回答