C# 中的内存泄漏

Memory Leak in C#(C# 中的内存泄漏)
本文介绍了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# 中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)