Even if you are "done" with the control, the page will access the control when it renders, so disposing them during construction doesn't make much sense. In one of your examples you are using one of the controls you just disposed, which also doesn't make sense.
Call Dispose when you are finished using the Control. The Dispose
method leaves the Control in an unusable state. After calling this
method, you must release all references to the control so the memory
it was occupying can be reclaimed by garbage collection.
The description of the Disposed event raised by the control also hints at the intended usage:
Occurs when a server control is released from memory, which is the
last stage of the server control lifecycle when an ASP.NET page is
requested.
Source: http://msdn.microsoft.com/en-us/library/system.web.ui.control.dispose.aspx
Source: http://msdn.microsoft.com/en-us/library/system.web.ui.control.disposed.aspx
See Also: https://stackoverflow.com/a/3151072/453277
So in theory:
- Build control tree.
- Page begins rendering.
- Page looks at controls added to tree.
- Controls have been disposed.
- Potential problems.
Here is the implementation of IDisposable
(from Control
). Note how it alters the container and event-related values.
public virtual void Dispose()
{
if (this.Site != null)
{
IContainer container = (IContainer)this.Site.GetService(typeof(IContainer));
if (container != null)
{
container.Remove(this);
EventHandler eventHandler = this.Events[Control.EventDisposed] as EventHandler;
if (eventHandler != null)
{
eventHandler(this, EventArgs.Empty);
}
}
}
if (this._occasionalFields != null)
{
this._occasionalFields.Dispose();
}
if (this._events != null)
{
this._events.Dispose();
this._events = null;
}
}
When to Dispose
That isn't to say you shouldn't dispose your resources; if a control needs to dispose resources, it is certainly free to do so. Perhaps a control accesses a database; I would wrap the database code inside a using
block inside the control.
In practicality, this style creates a large block of code for something which could be expressed more simply.
using (LiteralControl ltlText = new LiteralControl())
{
ltlText.Text = displayName;
cellAssociate.Controls.Add(ltlText);
}
// could become
cellAssociate.Controls.Add( new LiteralControl { Text = displayName } );