views:

601

answers:

2

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.

+4  A: 

I think it is safe. Page_Unload is supposed to be where cleanup is performed in the page life cycle. See http://msdn.microsoft.com/en-us/library/ms178472.aspx which says:

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Keltex
+4  A: 

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.

pbz