Why can .NET not have memory leaks?

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

    Here's an example of a memory leak in .NET, which doesn't involve unsafe/pinvoke and doesn't even involve event handlers.

    Suppose you're writing a background service that receives a series of messages over a network and processes them. So you create a class to hold them.

    class Message 
    {
      public Message(int id, string text) { MessageId = id; Text = text; }
      public int MessageId { get; private set; }
      public string Text { get; private set; }
    }
    

    OK, so far so good. Later on you realize that some requirement in the system could sure be made easier if you had a reference to the previous message available when you do the processing. There could be any number of reasons for wanting this.

    So you add a new property...

    class Message
    {
      ...
      public Message PreviousMessage { get; private set; }
      ...
    }
    

    And you write the code to set it. And, of course, somewhere in the main loop you have to have a variable to keep up with the last message:

      Message lastMessageReceived;
    

    Then you discover some days later than your service has bombed, because it has filled up all the available memory with a long chain of obsolete messages.

提交回复
热议问题