Memory leaks in .NET [closed]

2020-01-27 10:37发布

What are all the possible ways in which we can get memory leaks in .NET?

I know of two:

  1. Not properly un-registering Event Handlers/Delegates.
  2. Not disposing dynamic child controls in Windows Forms:

Example:

// Causes Leaks  
Label label = new Label();  
this.Controls.Add(label);  
this.Controls.Remove(label);  

// Correct Code  
Label label = new Label();  
this.Controls.Add(label);  
this.Controls.Remove(label);  
label.Dispose();

Update: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.


Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.

In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).

So, what are the various possible ways in which such a memory leak can happen?

14条回答
Rolldiameter
2楼-- · 2020-01-27 11:18

A lot of the things that can cause memory leaks in unmanaged languages can still cause memory leaks in managed languages. For example, bad caching policies can result in memory leaks.

But as Greg and Danny have said, there is no comprehensive list. Anything that can result in holding memory after its useful lifetime can cause a leak.

查看更多
Juvenile、少年°
3楼-- · 2020-01-27 11:19

Exceptions in Finalise (or Dispose calls from a Finaliser) methods that prevent unmanaged resources from being correctly disposed. A common one is due to the programmer assuming what order objects will be disposed and trying to release peer objects that have already been disposed resulting in an exception and the rest of the Finalise/Dispose from Finalise method not being called.

查看更多
登录 后发表回答