问题描述
有很多问题问如何检测 IDisposable 对象泄漏.答案似乎是你不能".
There are many questions SO asking how to detect IDisposable objects leak. It seems like the answer is "you can't".
我刚刚检查了最简单的测试用例,即 FxCop 10.0 不支持,带有 MSVS2010 的 ReSharper 4 不支持.
I just checked with the most trivial test case, that FxCop 10.0 doesn't do it, ReSharper 4 with MSVS2010 doesn't do it.
这对我来说似乎是错误的,比 C 中的内存泄漏更糟糕(至少我们已经建立了检测工具).
This seems wrong to me, worse than memory leaks in C (for which at least we have established tools to detect).
我在想:是否有可能使用反射和其他晦涩的高级技术,我可以在运行时注入检查,在终结器中查看 Dispose
是否已被调用?
I was thinking: Is it possible, using reflection and other obscure advanced techniques, that I can inject a check at runtime, in the finalizer to see whether Dispose
has been called?
WinDBG+SOS 的魔术技巧怎么样?
How about magic tricks with WinDBG+SOS?
即使没有现有的工具可以做到这一点,我也想知道这在理论上是否可行(我的 C# 不是很敏锐).
Even if there aren't existing tools to do it, I'd like to know whether this is theoretically possible (my C# isn't very sharp).
想法?
注意这个问题的标题可能具有误导性.这里真正的问题应该是IDisposable
对象是否已经Disposed()
正确.被 GC 处理不算数,因为我认为这是一个错误.
NOTE This question's title might have been misleading. The real question here should be whether a IDisposable
object has been Disposed()
properly. Getting disposed by the GC doesn't count since I regard that as a mistake.
编辑:解决方案:.NET Memory Profiler 完成这项工作.我们只需要在程序结束时发送几个 GC.Collect()
即可让我们的分析器正确获取统计信息.
Edit: Solution: .NET Memory Profiler does the job. We just need to spam several GC.Collect()
at the end of the program to enable our profiler to correctly pick up the stats.
推荐答案
你的搜索不够努力.有很多 .NET 内存分析器会在你的程序运行时查看它,让你知道你的内存在哪里/如何使用(以及什么正在泄漏它).
You didn't search hard enough. There are plenty of .NET Memory Profilers out there that will look at your program as it runs and let you know where/how your memory is used (and what is leaking it).
我会检查以下任何一项:
I would check out any of the following:
微软的 CLR 内存分析器(免费)
RedGate ANTS 内存分析器
JetBrain 的 DotTrace(也包括代码分析器)
SciTech .NET 内存分析器
更新
SciTech 的 .NET Memory Profiler 有一项名为Dispose Tracker"的功能,可满足 OP 要求仅跟踪其应用程序中的 Dispose 调用的要求.
SciTech's .NET Memory Profiler has a feature called 'Dispose Tracker' that fits the bill for the OP's request of tracking only the Dispose calls in their application.
这篇关于检测“泄漏"IDisposable 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!