Should I always disconnect event handlers in the Dispose method?

前端 未结 3 1057
日久生厌
日久生厌 2020-11-30 07:10

I\'m working in C# and my workplace has some code standards. One of them is that each event handler we connect (such as KeyDown) must be disconnected in the

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 08:01

    I had a major GDI leak in my application if I didn't unregister the event handlers in the Dispose() of a user control that was being dynamically created and destroyed. I found the following in the Visual Studio 2013 help, in the C# Programming Guide. Note the stuff I have put in italics:

    How to: Subscribe to and Unsubscribe from Events

    ...snip...

    Unsubscribing

    To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object.

    Note that in my case both the publisher and the subscriber were in the same class, and the handlers are not static.

提交回复
热议问题