EventHandlers and C# Classes destructor/Dispose

前端 未结 2 1111
渐次进展
渐次进展 2021-02-03 23:29

I\'m a bit confused about C# Classes and their deconstructor.

I have to consume a few event handlers in a class instance I\'m getting in the constructor:



        
2条回答
  •  星月不相逢
    2021-02-03 23:55

    Don't do it in the destructor, because it won't be called while the event handlers are attached : when you attach an instance method of Foo as a handler for an event of Bar, Bar will hold a reference to Foo, so Foo won't be garbage collected, and its destructor won't be called.

    You should implement IDisposable, and dispose your object explicitly

    public void Dispose()
    {
        if (handler != null)
        {
            handler.Load -= Load;
            handler.Close -= Close;
        }
    }
    

提交回复
热议问题