Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to believe Page_Unload will always run and is a good place for Dispose() code?

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.

like image 249
MatthewMartin Avatar asked Apr 01 '09 02:04

MatthewMartin


People also ask

What will happen if we call Dispose() method directly?

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.

What does Dispose do?

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.

Why to use Dispose method in C#?

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. .

When should I use dispose?

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.


1 Answers

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.

like image 108
pbz Avatar answered Nov 02 '22 04:11

pbz