0

I have a Custom control CustomContainer, that contains another series of custom controls (CustomButtons).

So control CustomContainer has 5 CustomButtons's.

Each CustomButtons has and Click eventhandler that is wired up in the constructor of CustomContainer.

Do I need to write an override Dispose for Control CustomContainer (As it inherits from UserControl there is a Dispose) to un-wire these CustomButtons event handlers? Is the standard Disposing sufficient or will I have a memory leak here?

Thanks, A.

AidanO
  • 868
  • 1
  • 11
  • 33

3 Answers3

2

In most cases involving control events, one can abandon events without disposing them and not run into trouble, because the event publisher and subscriber will generally go out of scope at about the same time. In some ways, this is unfortunate, since if event cleanup were considered necessary for correctness, there would probably be language support for it, and any decently-written code would clean up events as a matter of course.

The problem is that anything keeps an abandoned event publisher from being garbage-collected will also prevent any of its subscribers from being garbage-collected; if those subscribers publish any events of their own, all of their subscribers will likewise be needlessly sheltered from garbage-collection, etc. Suppose, for example, that one has a program that's working beautifully, but one adds an event to let a form know when another form is opened or closed, so that each form can have a "Windows" menu listing other open forms. Nice feature. If, however, a form is disposed without unsubscribing from the event providing such notifications, such failure may prevent the form, or any of its controls, nor any other objects to which those things hold references, from ever being collected. A significant memory leak, though one which will likely only cause problems if multiple documents are opened and closed during the lifetime of the program, and which may thus not be discovered except by the end user.

My recommendation would be to use the form's Disposed event to handle event cleanup. One could change the Dispose code generated by the designer, and the designer would probably leave those changes alone, but given that the Disposed event exists, I would think it cleaner to avoid any tinkering with the designer-generated files.

supercat
  • 77,689
  • 9
  • 166
  • 211
1

No, you do not need to implement IDisposable and implement Dispose() only for un-subscription from event handlers you have. The presence of that event handlers you have (button clicks, according to post) will not cause a memory leaks.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

IDisposable is used to clean up unmanaged resources. All the managed resource are cleaned up by the garbage collector. When there are no more references to the object , the next time the GC run it will free up everything not accessible from the application.