托管代码中是否可能存在内存泄漏?(特别是 C# 3.0) [英] Is it possible to have a memory leak in managed code? (specifically C# 3.0)

查看:25
本文介绍了托管代码中是否可能存在内存泄漏?(特别是 C# 3.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个分层数据结构:

For instance if I have a hierarchical data structure:

class Node
{
    public List<Node> children;
}

然后在其中一个父母中填充到多个级别:

and it is populated to many levels down then in one of the parents go:

myNode.children.Clear();

这将清除对直接子代的所有引用 - 但是那些直接子代所引用的所有孙子、孙子等又如何呢?C# 是否足够聪明,知道不再需要它们并且它们将被垃圾收集?

which will clear all the references to the immediate children - but how about all the grand children, grand grand children etc. that were referenced by those immediate children? Is C# clever enough to know they are no longer needed and they will be garbage collected?

我读过使用 WPF 数据绑定而不实现接口 INotifyChanged 会导致内存泄漏:http://blogs.msdn.com/b/micmcd/archive/2008/03/07/avoiding-a-wpf-memory-leak-with-databinding-black-magic.aspx,这在托管环境中怎么可能?

I have read using WPF data binding without implementing interface INotifyChanged can cause memory leaks: http://blogs.msdn.com/b/micmcd/archive/2008/03/07/avoiding-a-wpf-memory-leak-with-databinding-black-magic.aspx, how is that possible in a managed environment?

推荐答案

是的,垃圾收集器会计算出孙子等是垃圾.基本上,如果没有办法访问一个对象,它就被认为是垃圾并且可以收集.

Yes, the garbage collector will work out that the grandchildren etc are garbage. Basically, if there's no way of getting to an object, it's considered garbage and eligible for collection.

至于在托管代码中内存泄漏"是如何可能的——通常是如果您最终得到一个可通过对象引用访问的对象,但您无法最终清除"" 那些通过 API 的引用.

As for how memory "leaks" are possible in managed code - it's typically if you end up with an object which is reachable via object references, but where there's no way you can end up "clearing" those references via an API.

您引用的博文就是这种情况:

That's the case in the blog post you quoted:

WPF 检查以查找实现 INotifyProperyChanged 的​​内容存在问题.如果数据绑定没有实现这个接口,那么它会在一个全局表中创建一个记录.该记录不会被清除,因为 WPF 无法检查何时不再需要该数据库记录.

There is an issue where WPF checks to find things that implement INotifyProperyChanged. If there is a databinding to something not implementing this interface, then it makes a record in a global table. That record doesn't get cleaned up, as WPF has no way of checking when that DB record is no longer needed.

所以有这个全局表维护引用,你没有办法表明表中的一个项目可以被清除.

So there's this global table maintaining references, and you have no way of indicating that an item in the table can be cleared.

这篇关于托管代码中是否可能存在内存泄漏?(特别是 C# 3.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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