What are ways to solve Memory Leaks in C#

前端 未结 10 2009
生来不讨喜
生来不讨喜 2021-02-14 14:50

I\'m learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I\'m looking for wisdom learn

10条回答
  •  生来不讨喜
    2021-02-14 15:39

    The first thing with GC is that it is non-deterministic; if you want a resource cleaned up promptly, implement IDisposable and use using; that doesn't collect the managed memory, but can help a lot with unmanaged resources and onward chains.

    In particular, things to watch out for:

    • lots of pinning (places a lot of restrictions on what the GC can do)
    • lots of finalizers (you don't usually need them; slows down GC)
    • static events - easy way to keep a lot of large object graphs alive ;-p
    • events on an inexpensive long-life object, that can see an expensive object that should have been cleaned up
    • "captured variables" accidentally keeping graphs alive

    For investigating memory leaks... "SOS" is one of the easiest routes; you can use SOS to find all instances of a type, and what can see it, etc.

提交回复
热议问题