Practical use of System.WeakReference

后端 未结 4 1448
鱼传尺愫
鱼传尺愫 2021-01-30 21:35

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 h

4条回答
  •  名媛妹妹
    2021-01-30 22:10

    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.

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

    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.

    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!

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

提交回复
热议问题