本文介绍了在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()和pretend不存在(和辍学从code的所有引用),还有在object1的活动的隐式引用将prevent 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#中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 16:53