What are ways to solve Memory Leaks in C#

前端 未结 10 2032
生来不讨喜
生来不讨喜 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条回答
  •  萌比男神i
    2021-02-14 15:37

    In general, the less you worry about memory allocation in C#, the better off you are. I would leave it to a profiler to tell me when I'm having issues with collection.

    You can't create memory leaks in C# in the same way as you do in C++. The garbage collector will always "have your back". What you can do is create objects and hold references to them even though you never use them. That's a code smell to look out for.

    Other than that:

    • Have some notion of how frequently collection will occur (for performance reasons)
    • Don't hold references to objects longer than you need
    • Dispose of objects that implement IDisposable as soon as you're done with them (use the using syntax)
    • Properly implement the IDisposable interface

提交回复
热议问题