views:

468

answers:

1

Hi

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!

A: 

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.

OregonGhost
That does make sense. But why do those child controls still live after Dipose was called on the parent control? How is that possible?
John
The controls should not live after being disposed of. Try to access a property, it should throw an ObjectDisposedException, or whatever the name is. However, the underlying *objects* will live until all references to them vanish, which is why it is important to unsubscribe from outside events.
OregonGhost