I'm hunting memory leaks in an asp.net website. One that I found was that the code wasn't releasing event handlers when controls were no longer needed. I went with the disposing pattern as shown on MSDN to clean them up, and put the calls to remove the event handlers inside the if (disposing)
block since they were managed resources, but unless I go through and add destructors to each page and have them all manually dispose the controls nothing fires until the finalizer cleans up the mess. Doing it that way would be brittle and make re-introducing a leak in the future relatively easy; would I be better off ignoring the convention about not touching non-managed objects in code ran by the finalizer?
// Design pattern for a base class.
public class Base: IDisposable
{
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
myControl.SomeEvent -= SomeEventHandler;
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
}