Why can .NET not have memory leaks?

前端 未结 16 1228
春和景丽
春和景丽 2020-12-07 16:17

Ignoring unsafe code, .NET cannot have memory leaks. I\'ve read this endlessly from many experts and I believe it. However, I do not understand why this is so.

It is

相关标签:
16条回答
  • 2020-12-07 17:16

    If you aren't referring to applications using .NET, which these answers discuss very well, but are actually referring to the runtime itself, then it technically can have memory leaks, but at this point the implementation of the garbage collector is probably nearly bug-free. I have heard of one case in which a bug was found where something in the runtime, or maybe just in the standard libraries, had a memory leak. But I don't remember what it was (something very obscure), and I don't think I would be able to find it again.

    0 讨论(0)
  • 2020-12-07 17:17

    Well .NET has a garbage collector to clean things up when it sees fit. This is what separates it from other unmanaged languages.

    But .NET can have memory leaks. GDI leaks are common among Windows Forms applications, for example. One of the applications I've helped develop experiences this on a regular basis. And when the employees in the office use multiple instances of it all day long it's not uncommon for them to hit the 10,000 GDI object limit inherent to Windows.

    0 讨论(0)
  • 2020-12-07 17:18

    .NET can have memory leaks but it does a lot to help you avoid them. All reference type objects are allocated from a managed heap which tracks what objects are currently being used (value types are usually allocated on the stack). Whenever a new reference type object is created in .NET, it is allocated from this managed heap. The garbage collector is responsible for periodically running and freeing up any object that is no longer used (no longer being referenced by anything else in the application).

    Jeffrey Richter's book CLR via C# has a good chapter on how memory is managed in .NET.

    0 讨论(0)
  • 2020-12-07 17:19

    Remember, the difference between a cache and a memory leak is policy. If your cache has a bad policy (or worse, none) for removing objects, it is indistinguishable from a memory leak.

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