Given that the Control class implements IDisposable, I would think that ASP.Net is at least capable of triggering a Dispose cascade as the Page finishes it\'s life-cycle on
It's done for you. Look at UnloadRecursive()
from System.Web.UI.Control
in Reflector, which is called by ProcessRequestCleanup()
.
No, you should not call Dispose on controls, that is being done. You are responsible for other Disposable objects you create outside the Control structure (FileStreams etc).
This follows from a general .NET principle: The Page is the owner of the Controls and therefore required to cascade the (explicit) Dispose to them. For the actual code you will have to Reflector the code for Web.UI.Control.
This article on The ASP.NET Page Life Cycle states that:
"Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed."
I would take that "any cleanup" means disposal of controls etc. I can't imagine that the designers of the ASP.NET framework would have overlooked that and nobody would have noticed.
Interpreted differently, there's more complexity to this question than meets the eye.
Sure Disposed
gets called, but does it do anything? It depends.
If you've subscribed to the Disposed
event of a page or control and are banking on it being called per-request, you might be in for a surprise. Yes, technically speaking ProcessRequestCleanup()
calls it for you, but have a look at what it actually calls:
public virtual void Dispose()
{
IContainer service = null;
if (this.Site != null)
{
service = (IContainer) this.Site.GetService(typeof(IContainer));
if (service != null)
{
service.Remove(this);
EventHandler handler = this.Events[EventDisposed] as EventHandler;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
if (this._occasionalFields != null)
{
this._occasionalFields.Dispose();
}
}
Without a design surface, this code essentially does nothing at run-time, meaning your Disposed
handlers will never execute.
Lesson is don't rely on Disposed
handlers to execute per request. You can override it to guarantee something executes, but Unloaded
is a much safer bet.