Why can .NET not have memory leaks?

前端 未结 16 1427
春和景丽
春和景丽 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:10

    I suppose it is possible to write software, e.g. the .NET runtime environment (the CLR), that does not leak memory if one is careful enough. But since Microsoft does issue updates to the .NET framework via Windows Update from time to time, I'm fairly sure that there are occasional bugs even in the CLR.

    All software can leak memory.

    But as others have already pointed out, there are other kinds of memory leaks. While the garbage collector takes care of "classic" memory leaks, there's still, for example, the problem of freeing so-called unmanaged resources (such as database connections, open files, GUI elements, etc.). That's where the IDisposable interface comes in.

    Also, I've recently come across with a possible leaking of memory in a .NET-COM interop setting. COM components use reference counts to decide when they can be freed. .NET adds yet another reference counting mechanism to this which can be influenced via the static System.Runtime.InteropServices.Marshal class.

    After all, you still need to be careful about resource management, even in a .NET program.

提交回复
热议问题