实际使用System.WeakReference的实际、System、WeakReference

2023-09-04 22:44:42 作者:べ說好不放手的。

我明白 System.WeakReference 的做法,但似乎我不能把握是它可能是有用的实际例子。本身在我看来,这个类是,好了,一个黑客。在我看来,有解决,其中一个WeakReference的是用在我见过的例子的问题等,更好的手段。什么是的,你真的得使用WeakReference的典型的例子?我们不是试图让远的远离这种类型的行为和使用这个类的?

I understand what System.WeakReference does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get farther away from this type of behavior and use of this class?

推荐答案

一个有用的例子是谁跑DB4O面向对象数据库的家伙。还有,在WeakReferences作为一种光缓存:它会保持你的对象在内存中只只要你的应用程序做,让你把一个真实的缓存之上

One useful example is the guys who run DB4O object oriented database. There, WeakReferences are used as a kind of light cache: it will keep your objects in memory only as long as your application does, allowing you to put a real cache on top.

另一个用途是在弱的事件处理程序的执行。目前,在.NET应用程序的内存泄漏的一大来源是忘记删除事件处理程序。例如,

Another use would be in the implementation of weak event handlers. Currently, one big source of memory leaks in .NET applications is forgetting to remove event handlers. E.g.

public MyForm()
{
    MyApplication.Foo += someHandler;
}

请参阅问题?在上面的代码片段,MyForm的将永远只要MyApplication的是活在记忆维持生命在内存中。在事件处理程序创建10 MyForms,则全部关闭,你的10 MyForms仍然会在内存中,不停地活着。

See the problem? In the above snippet, MyForm will be kept alive in memory forever as long as MyApplication is alive in memory. Create 10 MyForms, close them all, your 10 MyForms will still be in memory, kept alive by the event handler.

输入的WeakReference。您可以通过建立在WeakReferences弱的事件处理程序,以便someHandler是一个弱的事件处理程序MyApplication.Foo,从而修复您的内存泄漏!

Enter WeakReference. You can build a weak event handler using WeakReferences so that someHandler is a weak event handler to MyApplication.Foo, thus fixing your memory leaks!

这不只是理论。达斯汀·坎贝尔从DidItWith.NET博客贴出弱的事件处理程序的实现使用System.WeakReference。

This isn't just theory. Dustin Campbell from the DidItWith.NET blog posted an implementation of weak event handlers using System.WeakReference.