Is it possible to believe that Page_Unload will always work and is a good place for Dispose () code?

I am familiar with the try {} finally {} template, using the use () {} template as methods to call Dispose (), but for an ASP.NET page, is it also safe to delete objects created in the page area in the Page_Unload event? Does it make sense to override the Page Dispose () method?

I'm not sure which code triggers the Page_Unload event or the Dispose () method, so I don’t know which guarantees will be met.

+6
c # dispose
source share
2 answers

The unload event is raised in the control life cycle just before the deletion. Since the page itself is a control, an unload event is also generated for it. Each control that you add to a page will be part of the page life cycle. Therefore, if you have a control that needs to perform some cleanup, the control itself must handle any possible cleanup by itself. You should not worry about this if the control is added to the page and correctly follows the principle of encapsulation.

The documentation says that you should even use this "for final cleanup for certain controls, such as closing control-related connections." My recommendation would be to avoid a discharge event. If possible, make the cleanup code sooner rather than later, so use "use" if you can. In a way, this is like choosing between using a β€œglobal” variable as opposed to a local variable, the latter being preferable.

+9
source share

I think it is safe. It is assumed that Page_Unload will be cleared 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 for final cleanup for specific control measures, such as closing databases associated with specific ones.

For the page itself, use this event to perform the final cleanup work, for example, closing open files and database connections or completing logging or other tasks related to the request.

+5
source share

All Articles