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 Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Dispose improves performance and optimizes memory by releasing unmanageable objects and scarce resources, like Graphics Device Interface (GDI) handles used in applications with restricted Windows space. The Dispose method, provided by the IDisposable interface, implements Dispose calls.
It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary. At runtime C#, C++ destructors are automatically converted to Finalize method. .
The Dispose Method—Explicit Resource Cleanup The Dispose method generally doesn't free managed memory—typically, it's used for early reclamation of only the unmanaged resources to which a class is holding references. In other words, this method can release the unmanaged resources in a deterministic fashion.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With