I have an application in which a lot of memory leaks are present. For example if a open a view and close it 10 times my memory consumption rises becauses the views are not compl
Often memory leaks are introduced when managed types use unmanaged resources without due care.
A classic example of this is the System.Threading.Timer
which takes a callback method as a parameter. Because the timer ultimately uses an unmanaged resource a new GC root is introduced which can only be released by calling the timer's Dispose
method. In this case your type should also implement IDisposable
otherwise this object can never be garbage collected (a leak).
You can write a unit test for this scenario by doing something similar to this:
var instance = new MyType();
// ...
// Use your instance in all the ways that
// may trigger creation of new GC roots
// ...
var weakRef = new WeakReference(instance);
instance.Dispose();
instance = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.IsFalse(weakRef.IsAlive);