C# 中的内存泄漏 [英] Memory Leak in C#

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

问题描述

当您确保所有句柄、实现 IDispose 的东西都被释放时,在托管系统中是否有可能泄漏内存?

Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

会不会有一些变量被遗漏的情况?

Would there be cases where some variables are left out?

推荐答案

事件处理程序是非明显内存泄漏的常见来源.如果您从 object2 订阅 object1 上的事件,然后执行 object2.Dispose() 并假装它不存在(并从您的代码中删除所有引用),则 object1 的事件中有一个隐式引用将阻止 object2垃圾收集.

Event Handlers are a very common source of non-obvious memory leaks. If you subscribe to an event on object1 from object2, then do object2.Dispose() and pretend it doesn't exist (and drop out all references from your code), there is an implicit reference in object1's event that will prevent object2 from being garbage collected.

MyType object2 = new MyType();

// ...
object1.SomeEvent += object2.myEventHandler;
// ...

// Should call this
// object1.SomeEvent -= object2.myEventHandler;

object2.Dispose();

这是一种常见的泄漏情况 - 忘记轻松取消订阅事件.当然,如果 object1 被收集,object2 也会被收集,但直到那时.

This is a common case of a leak - forgetting to easily unsubscribe from events. Of course, if object1 gets collected, object2 will get collected as well, but not until then.

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

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