Even if you are "done" with the control, the page will gain access to the control when it displays, so getting rid of them during construction does not make much sense. In one of your examples, you use one of the controls you control, which also makes no sense.
Call Dispose when you are done using the control. Dispose of the method leaves the control in an unusable state. After this method, you must free all references to the control so that the memory of this activity can be disposed of by garbage collection.
The description of the Disposed event raised by the control also indicates the intended use:
Occurs when the server control is freed from memory, the last stage of the server control life cycle when the ASP.NET page 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: fooobar.com/questions/513998 / ...
So, in theory:
- Build a control tree.
- The page starts rendering.
- The page looks at the controls added to the tree.
- The controls have been deleted.
- Potential problems.
Here is the implementation of IDisposable (from Control ). Notice how this changes the container and event 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 remove
This does not mean that you should not dispose of your resources; if control must manage resources, it is certainly free. The control may be accessing the database; I would wrap the database code inside the using block inside the control.
In practicality, this style creates a large block of code for something that can be expressed more simply.
using (LiteralControl ltlText = new LiteralControl()) { ltlText.Text = displayName; cellAssociate.Controls.Add(ltlText); }
source share