Correctly disposing user controls and child controls in C#

we are experiencing a few problems with the IDisposable pattern. In this case there is a user control 'ControlA' with a FlowLayoutPanel, which contains more usercontrols 'ControlB'.

When calling Dispose(bool), I check if disposing if true, and if IsDisposed is false. I then try to explicitly dispose each ControlB in the FlowLayoutPanel's Controls collection. However, if does not loop through all controls, only 3 of 8, or 2 of 4.

Dispose(bool disposing) { if (disposing) { if (!IsDisposed) { //unhook events etc. foreach(ControlB ctrl in flowlayoutpanel.Controls) //<-- there 8 controls ctrl.Dispose(); //<-- called 3 times only flp.Controls.Clear(); } } //make all members null }

My quesitons are: 1. Why is this happening? 2. What are best practices and expereinces you guys had with disposing user controls and thei child controls? E.g. do you unsubscribe event handlers at all times, etc.

Thanks!

-------------Problems Reply------------

You don't need to manually dispose controls that are child controls of the control that is being disposed, i.e. are in the Controls collection. The parent control will handle this automatically.

If you are being disposed, you must unsubscribe from events that are outside of your scope, i.e. that are members of objects that will stay alive, because they will otherwise keep you alive as well, despite being disposed. You don't need to unsubscribe from events in objects that are being disposed of as well, like your child controls.

Category:user controls Views:0 Time:2010-03-04

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.190 (s). 11 q(s)