“内存泄漏"剖析 [英] Anatomy of a "Memory Leak"

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

问题描述

在 .NET 中:

  • 什么是内存泄漏?
  • 如何确定您的应用程序是否泄漏?有什么影响?
  • 如何防止内存泄漏?
  • 如果您的应用程序存在内存泄漏,它会在进程退出或被终止时消失吗?或者即使在进程完成后,您的应用程序中的内存泄漏是否会影响系统上的其他进程?
  • 那么通过 COM Interop 和/或 P/Invoke 访问的非托管代码呢?

推荐答案

我见过的最好的解释是在免费的 编程基础电子书.

The best explanation I've seen is in Chapter 7 of the free Foundations of Programming e-book.

基本上,在 .NET 中,当引用的对象有根并且不能被垃圾回收时,就会发生内存泄漏.当您保留超出预期范围的引用时,会意外发生这种情况.

Basically, in .NET a memory leak occurs when referenced objects are rooted and thus cannot be garbage collected. This occurs accidentally when you hold on to references beyond the intended scope.

当您开始出现 OutOfMemoryExceptions 或您的内存使用量超出您的预期时(PerfMon 有很好的内存计数器),您就会知道存在泄漏.

You'll know that you have leaks when you start getting OutOfMemoryExceptions or your memory usage goes up beyond what you'd expect (PerfMon has nice memory counters).

了解 .NET 的内存模型是避免它的最佳方法.具体来说,了解垃圾收集器的工作原理以及引用的工作原理——我再次向您推荐电子书的第 7 章.此外,请注意常见的陷阱,可能最常见的是事件.如果对象 A 注册到对象 B 上的事件,则对象 A 将一直存在,直到对象 B 消失因为 B 持有对 A 的引用.解决方案是在完成后取消注册您的事件.

Understanding .NET's memory model is your best way of avoiding it. Specifically, understanding how the garbage collector works and how references work — again, I refer you to chapter 7 of the e-book. Also, be mindful of common pitfalls, probably the most common being events. If object A is registered to an event on object B, then object A will stick around until object B disappears because B holds a reference to A. The solution is to unregister your events when you're done.

当然,一个好的内存配置文件会让你看到你的对象图并探索你的对象的嵌套/引用,看看引用来自哪里以及哪个根对象负责(红门蚂蚁简介,JetBrains dotMemory,memprofiler 确实是不错的选择,或者您可以使用纯文本的 WinDbgSOS,但我强烈推荐商业/视觉除非您是真正的大师).

Of course, a good memory profile will let you see your object graphs and explore the nesting/referencing of your objects to see where references are coming from and what root object is responsible (red-gate ants profile, JetBrains dotMemory, memprofiler are really good choices, or you can use the text-only WinDbg and SOS, but I'd strongly recommend a commercial/visual product unless you're a real guru).

我相信非托管代码受其典型内存泄漏的影响,除了共享引用由垃圾收集器管理.最后一点我可能是错的.

I believe unmanaged code is subject to its typical memory leaks, except that shared references are managed by the garbage collector. I could be wrong about this last point.

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

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