Unit testing memory leaks

后端 未结 6 947
感情败类
感情败类 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 21:59

    That memory consumption increases is not necessarily an indication of a resource leak, since garbage collection is non deterministic and may not have kicked in yet. Even though you "let go" of objects, the CLR is free to keep them around as long as it deems enough resources are available on the system.

    If you know you do in fact have a resource leak, you may work with objects that have explicit Close/Dispose as part of their contract (meant for "using ..." constructs). In that case, if you have control over the types, you can flag disposal on the objects from their Dispose implementation, to verify that they have in fact been disposed, if you can live with lifecycle management leaking into the type's interface.

    If you do the latter, it is possible to unit test that contractual disposal takes place. I've done that on some occasions, using an application specific equivalent to IDisposable (extending that interface), adding the option for querying whether the object has been disposed. If you implement that interface explicitly on your type, it won't pollute its interface as much.

    If you have no control over the types in question, a memory profiler, as suggested elsewhere, is the tool you need. (For instance dotTrace from Jetbrains.)

提交回复
热议问题