Unit testing memory leaks

后端 未结 6 856
感情败类
感情败类 2021-02-12 21:20

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

6条回答
  •  无人及你
    2021-02-12 22:08

    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);
    

提交回复
热议问题