What are the most common (and often overlooked) causes of memory leaks in managed (.net) applications?

后端 未结 11 963
闹比i
闹比i 2021-02-04 09:32

Please can anyone recommend a quick checklist / best practice guide to help us avoid simple (but subtle) mistakes that cause could cause memory leaks in .net apps

I find

11条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 10:03

    To answer your last two questions:

    There are, by definition, no memory leaks in managed code. There are two kinds of leaks that can occur:

    • Objects are released when no references to the object are alive. If you still have a reference to an object, it will not be released. This happens for instance when you throw away a reference to an object that has registered for an event - if you don't manually unregister the event handler (or use a weak reference), the event will still reference the object, so it will not be released although you have no obvious reference to it anymore.
    • Unmanaged resources can be leaked. Typically, a wrapper for unmanaged resources implements IDisposable and will free the resource when you call Dispose. If you just throw away the object, it will not release the resource and therefore leak it.

    So, two rules of thumb are:

    • Unregister any event handler when you release an object, or use a weak reference for that (search on SO, it's explained somewhere).
    • If a class exposes a Dispose method, call it. If you use the object only temporarily, use the using construct. If you have members that implement IDisposable, implement IDisposable yourself and call the members' Dispose in your Dispose.

提交回复
热议问题