.NET 中的内存泄漏 [英] Memory leaks in .NET

查看:32
本文介绍了.NET 中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .NET 中有哪些可能导致内存泄漏的方法?

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

我知道两个:

  1. 未正确取消注册事件处理程序/代表.
  2. 不在 Windows 窗体中处理动态子控件:

示例:

// 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();

更新:这个想法是列出不太明显的常见陷阱(例如上面的).通常的概念是内存泄漏不是一个大问题,因为垃圾收集器.不像以前在 C++ 中那样.

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++.

大家讨论得很好,但让我澄清一下...根据定义,如果没有对 .NET 中的对象的引用,它将在某个时候被垃圾收集.所以这不是导致内存泄漏的方法.

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).

那么,发生这种内存泄漏的各种可能方式有哪些?

推荐答案

阻塞终结器线程.在终结器线程解除阻塞之前,不会对其他对象进行垃圾回收.因此,使用的内存量会越来越大.

Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow.

进一步阅读:http://dotnetdebug.ne​​t/2005/06/22/blocked-finalizer-thread/

这篇关于.NET 中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆