Disposing a HtmlControl

On the advice of Code Analysis in VS to call Dispose on an object (which I wasn't previuosly) I ended up with a method containing this:

using (var favicon = new HtmlLink
                         {
                             Href = "~/templates/default/images/cc_favicon.ico"
                         })
{
    favicon.Attributes.Add("rel", "shortcut icon");
    Header.Controls.Add(favicon);
}

This confused me slightly, if I dispose this object after adding it to the Controls collection is that such a good idea?

How does this still work? Is it because the Controls.Add method disposes the object after use as opposed to holding on to it?


I would say that this code shouldn't work but if you say it's working then the only things I can think of are:

  • Header.Controls.Add add a copy of the object so there is no problem disposing the original.
  • The Dispose method does not clean anything that is used later.
  • Hope this helps.


    If a method on favicon is called that uses any of the unmanaged resources it will give exception.

    From msdn:

    You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

    using statement msdn


    I assume that you code analysis gave you CA2000: Dispose objects before losing scope before you changed the code. The problem is that you shouldn't dispose your object because you want to use it even after returning from the method (it has been added to a collection).

    You can either suppress the message using the SuppressMessage attribute or you can rewrite you code to be really paranoid:

    var favicon = new HtmlLink { Href = "~/templates/default/images/cc_favicon.ico" };
    try {
      favicon.Attributes.Add("rel", "shortcut icon");
    }
    catch {
      favicon.Dispose();
      throw;
    }
    Header.Controls.Add(favicon);
    

    The normal flow of this code adds favicon to the collection that is then responsible for disposing it. However, the abnormal flow where favicon.Attributes.Add throws an exception will dispose favicon before propagating the exception.

    In most case, because the garbage collector will do its job eventually, you don't need the paranoid version of the code.

    链接地址: http://www.djcxy.com/p/9148.html

    上一篇: sys.maxunicode是什么意思?

    下一篇: 处理HtmlControl