Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Disposing the resources when process exits

while browsing the System.AppDomain in reflector found this gem that can be very useful to cleanup the resources  when the application exits.

The event, System.AppDomain.CurrentDomain.ProcessExit takes delegate which invokes the method to dispose the resources. When used along with anonymous delegates the syntax looks even pretty

 
private Resource1 MyResource;

// Constructor
public MyExternalResources() {

// Assign the value for objResource
MyResource = HelperClass.GetResource(..);

// Clean up the resources when the Current Application Domain exits
System.AppDomain.CurrentDomain.ProcessExit += delegate
{
// Close the resources
MyResource.Close();
}
}

No Comments