Memory Leak in 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# 中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的内存泄漏
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01