I’m familiar with the try{}finally{} pattern, the using(){} pattern as ways to ensure Dispose() gets called, but for an ASP.NET page, is it just as safe to Dispose of objects created in page scope on the Page_Unload event? Would it make sense to override the Page’s Dispose() method instead?
I’m not sure what code raises the Page_Unload event, or the Page Dispose() method, so I don’t know what the guarantees are that it will run.
The unload event is raised in the control life-cycle right before dispose. Since the page itself is a control the unload event is raised for it as well. Each control you add to the page will be part of the page life-cycle. So if you have a control that needs to do some cleanup, the control itself should handle any possible cleanup in itself. You should not have to worry about this, provided the control has been added to the page and properly follows the encapsulation principle.
The documentation says that you should use this even ‘to do final cleanup for specific controls, such as closing control-specific database connections.’ My recommendation would be to avoid the unload event. When possible do any cleanup code sooner rather than later, so use ‘using’ if you can. In a way, it’s like the choice between using a ‘global’ variable as opposed to a local variable, the latter is preferable.