Why would I need to call dispose on ASP.NET Controls?

后端 未结 1 1969
独厮守ぢ
独厮守ぢ 2020-12-06 17:25

I\'m doing some ASP.NET development in VS and have just found an interesting little code suggestion (I think they come from coderush but I could be wrong).

Whenever

相关标签:
1条回答
  • 2020-12-06 18:16

    You shouldn't actually do this. What you need to do is make sure that listingTable is in the Controls collection so that it will be disposed when the Page is disposed. The listingTable object is then responsible for properly disposing all of its children.

    Which is why all Control objects implement the IDisposable interface. That way each parent control can call Dispose on all of its children without first having to test/cast each one. Each control is individually responsible for determining whether it actually has anything that needs to be cleaned up when its Dispose method is called.

    The docs are not wrong. Any properly-written object that implements IDisposable and has state data that is actually cleaned up during the dispose process should throw an ObjectDisposedException if any of its public/protected/internal properties or methods are accessed after it has been disposed. (Assume invalid state after Dispose has been called.) Some types will ignore this rule if they don't actually have anything to clean up, and don't have to worry about invalid state.

    The reason you're getting a suggestion to wrap it in a using block is because the analyzer doesn't realize that listingTable will dispose its Rows collection, which will dispose each of the row objects that have been added to it. Also, if an exception is thrown between HtmlTableRow tableRow = new HtmlTableRow() and listingTable.Rows.Add(tableRow), the HtmlTableRow object will be 'orphaned' and not be in any other object's IDisposable hierarchy. Code Analysis wants you to use a try/finally block to immediately dispose of the HtmlTableRow if this happens.

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