Does ASP.Net call Dispose on the Page/Controls in a page, or must I do this?

前端 未结 4 654
小蘑菇
小蘑菇 2020-12-18 21:01

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

相关标签:
4条回答
  • 2020-12-18 21:18

    It's done for you. Look at UnloadRecursive() from System.Web.UI.Control in Reflector, which is called by ProcessRequestCleanup().

    0 讨论(0)
  • 2020-12-18 21:25

    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.

    0 讨论(0)
  • 2020-12-18 21:36

    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.

    0 讨论(0)
  • 2020-12-18 21:38

    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.

    0 讨论(0)
提交回复
热议问题