Write. net Program We often encounter how to release resources correctly and execute destructor to improve the performance of your programs, though. Net has the GC function, but it is worth doing well to release resources manually in real time. You do not have to wait for the GC policy to call the recycle mechanism, and may destroy unmanaged resources, for example, sqlconnection, We have to re-generate unmanaged resources.
Below Code In vs2005
The following code is a class that supports dispose and stores it in app_code. Pay attention to reference the system. Web component.
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
/// <Summary>
/// Summary description for disposeclass
/// </Summary>
Public class disposeclass: idisposable
{
Public disposeclass ()
{
}
/**/
/// <Summary>
/// Whether the object has been destroyed
/// </Summary>
Private bool disposed;
/**/
/// <Summary>
/// Finalize Function
/// </Summary>
~ Disposeclass ()
{
// This destructor is automatically cleared when the user exits the app.
System. Web. httpcontext. Current. response. Write ("Object destroyed <br> ");
// Clear managed resources
Dispose (false );
}
// Clear the Code Location of hosted and unmanaged resources. Do not reverse it.
// Otherwise, when a managed object has been recycled by GC,
// Call its dispose method. The system will trigger an objectdisposedexception exception.
Public void dispose ()
{
/* Clear unmanaged Resources
**/
System. Web. httpcontext. Current. response. Write ("manually destroy an object <br> ");
Dispose (true );
// Notify GC, even if it has been destroyed, you don't have to worry about it...
GC. suppressfinalize (this );
}
/// <Summary>
/// Releases unmanaged and-optionally-managed resources
/// </Summary>
/// <Param name = "disposing"> <C> true </C> to release both managed and unmanaged resources; <C> false </C> to release only unmanaged resources. </param>
Protected void dispose (bool disposing)
{
If (! Disposed)
{
If (disposing)
{
// This function is called manually. You can clear managed resources here.
}
// Clear unmanaged Resources
}
Disposed = true;
}
}
call:
Create a page
put a button to execute the call.
protected void button#click (Object sender, eventargs E)
{< br> // manually release 1
disposeclass testclass1 = new disposeclass ();
testclass1.dispose ();
// manually release 2
using (disposeclass testclass2 = new disposeclass ()
{< br> response. write ("dispose will be automatically called after this using lifecycle
");
}< BR >}< br> how to let the program execute the Destructor ~ Disposeclass (): In Windows testing, this destructor is called when you exit the current form or close the app, but you do not know how to test it on the web, if you know anything, please let me know. Thank you.
love Leung because of understanding