0

Is it necessary to call Dispose on a control / object that was dynamically loaded via LoadControl and added to the page's control tree?

etc
  • 622
  • 4
  • 10
  • 1
    No, as soon as the response is complete, the runtime is free to clean everything up associated with the request, including the page object itself. That applies to dynamically loaded controls too because they are part of the page's control collection. That should be obvious since you must recreate them on every postback. – Tim Schmelter Dec 12 '11 at 20:13
  • Right, but does the garbage collector do the work here or is the control's Dispose method called as part of the page lifecycle? – etc Dec 12 '11 at 20:14

1 Answers1

0

No, as soon as the response is complete, the runtime is free to clean everything up associated with the request, including the page object itself. That applies to dynamically loaded controls too because they are part of the page's control collection. That should be obvious since you must recreate them on every postback.

You should override dispose if your UserControl uses unmanaged resources(f.e. database connection). The control itself will be disposed implicitely before the page gets disposed. This is the order of events at the end of the page's lifecycle:

  • Control: Unload(recursive)
  • Control: Dispose(recursive)
  • Page: Unload
  • Page: Dispose

As a hint, classes that implement IDisposable should be disposed as soon as you're done with it(UserControl does not). But usually you would do it by using the using-statement.

Resources:

But does the garbage collector do the work here or is the control's Dispose method called as part of the page lifecycle?

Calling Dispose does not prioritize the object for garbage collection. It simply unloads the object’s (unmanaged) resources from memory. Calling Dispose does not deallocate the object from memory. Only the GC does that when it performs a collection of the generation in which the object resides(from first link above).

So i think that you are misunderstanding dispose or/and the garbage-collector.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • No, I get what the GC does. The control in question has unmanaged resources associated and overrides the Dispose method. The question was simply whether I should call Dispose manually or allow the page's lifecycle handle it. I was unsure whether a control loaded via LoadControl would have it's Dispose method called by the page lifecycle or via the GC. I'd rather not have the GC do it as that increases the likelihood of the control ending up in Gen 1 GC. – etc Dec 13 '11 at 00:35