locked
A List Clear question RRS feed

  • Question

  • Hello,

    I have List list1 and I add a few windows (or forms) to it.  At one point I call list1.Clear() does this destroy all the windows I put in it (I assume the garbage collector does it)?  And if so does it do it right away?   Will it cause the Window to fire off a Closing event?

    none
    • Edited by ashlar Thursday, October 16, 2008 3:06 PM
    Thursday, October 16, 2008 3:03 PM

Answers

  • Just like any other .NET object, the lifetime of it is controlled by the references to it.  The lifetime of a control or form is also controlled by its Handle property.  As long as there's a Handle, there's a reference.  Releasing the handle is done explicitly.  Either by you calling Close() or by Windows Forms disposing handles in response to the user clicking the close icon.  So, clearing your list probably doesn't destroy anything.  And forgetting to clear the list probably produces a leak.
    Hans Passant.
    • Proposed as answer by JohnWein Thursday, October 16, 2008 9:05 PM
    • Marked as answer by Zhi-Xin Ye Wednesday, October 22, 2008 11:38 AM
    Thursday, October 16, 2008 3:40 PM

All replies

  • Hi,

    GC uses the non-deterministic algorithm to destroy / clear the objects in heap memory. When you call, "list1.Clear()", it won't destroy the "Form" object immediately. These will be cleared only after GC got invoked, where as list.clear() removes all the references between the list and the form objects, there by making them ready for Disposing.

    Here is one of the best articles on GC : http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

    Regards,
    Hemanth.
    Hemanth .NET Professional
    Thursday, October 16, 2008 3:12 PM
  • Just like any other .NET object, the lifetime of it is controlled by the references to it.  The lifetime of a control or form is also controlled by its Handle property.  As long as there's a Handle, there's a reference.  Releasing the handle is done explicitly.  Either by you calling Close() or by Windows Forms disposing handles in response to the user clicking the close icon.  So, clearing your list probably doesn't destroy anything.  And forgetting to clear the list probably produces a leak.
    Hans Passant.
    • Proposed as answer by JohnWein Thursday, October 16, 2008 9:05 PM
    • Marked as answer by Zhi-Xin Ye Wednesday, October 22, 2008 11:38 AM
    Thursday, October 16, 2008 3:40 PM