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

后端 未结 11 980
闹比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 09:44

    I can start to suggest that one should always be aware of IDisposable objects and how to properly dispose them. Also, be very careful with the state in you app. Grab only objects when it's absoluttly necessary. If object A is goind to live for a long period of time in your app, always try not making dependencies between A and other objects.

    0 讨论(0)
  • 2021-02-04 09:47

    Check for static variables which don't need to be there in the memory after usage, check for event handling references, any finalizaers which are blocking other finalizers from being collected and also if there are any un managed references to any DLLs or COM+ objects

    0 讨论(0)
  • 2021-02-04 09:48

    The short answer is non-obvious references.

    To add some details:

    • Statics are not collected until AppDomain is collected (which may equal process shutdown)
    • Events (remember to unsubscribe)
    • Blocked finalizers (finalizers are run sequentially so any blocking finalizer will prevent all other finalizable objects from being collected). Example includes finalizers that can't get to a STA thread.
    • Deadlocked thread will never release roots
    • Forgetting to call Monitor.Exit() (e.g. when used with a timeout or across methods) may cause a deadlock which in turn may cause a leak
    0 讨论(0)
  • 2021-02-04 09:48

    Number one would be event handlers that are attached and never detached.

    If the subscriber to the event lives longer than the producer of the event and the subscriber doesn't disconnect the event handler then object firing the events will remain alive as there's still a reference to it through the subscribing object.

    0 讨论(0)
  • 2021-02-04 09:57

    Circular references in value-classes (commonly in the model-layer of your application) can easily hide their leaks as well. In theory, don't do them, in practice, be aware whenever you need to do them :)

    0 讨论(0)
  • 2021-02-04 09:59

    The number one cause of memory leaks in managed applications, in my opinion, is mistakenly believing that you have a memory leak, when in fact you haven't measured properly. Be sure to use a memory profiler to measure exactly what kind of memory leak you have. You may find that you have some other problem.

    But when the leak is real, the major cause would be references to objects keeping those objects live when they're not really needed. Implementing a using statement for almost all objects implementing IDisposable is a good start. The only exception I know of is WCF proxy classes, which should be accessed with a try/catch/finally, and not a using statement.

    0 讨论(0)
提交回复
热议问题