C# 如何避免内存泄漏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/794466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:28:23  来源:igfitidea点击:

How to avoid Memory Leaks?

c#memory-leaks

提问by Josh

What are some tips I can use to avoid memory leaks in my applications? Are there any gotchas or pitfalls that I can look out for?

我可以使用哪些技巧来避免应用程序中的内存泄漏?有什么我可以注意的陷阱或陷阱吗?

采纳答案by Otávio Décio

Call Dispose on IDisposable objects or use the usingclause. That should take care of most of the leaks I can think of.

对 IDisposable 对象调用 Dispose 或使用using子句。这应该可以解决我能想到的大多数泄漏问题。

回答by neouser99

It's managed code, that c#, so you have to try hard to leak memory :P

它是托管代码,即 c#,因此您必须努力泄漏内存:P

Try google: http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=Mbp&q=c%23+memory+leaks&btnG=Search

试试谷歌:http: //www.google.com/search?hl=en&client =firefox-a&rls =org.mozilla%3Aen-US%3Aofficial&hs =Mbp&q =c%23+memory+leaks&btnG= Search

回答by Kasper Holdum

As mentioned by ocdecio be sure to call Dispose on Idisposable objects, and remember to remove event handlers when you're done with an object. When building classes that works with unmanaged resources, be sure to implement Idisposable, so the user will know that there are critical resources that'll need to be disposed of.

正如 ocdecio 所提到的,一定要在 Idisposable 对象上调用 Dispose,并记住在完成对象后删除事件处理程序。在构建使用非托管资源的类时,一定要实现 Idisposable,这样用户就会知道有需要处理的关键资源。

Also, even though garbage collections do quite a bit a work for you, you should get rid of references to objects that you're done with. Else they'll still have a root, and they won't be GC'ed.

此外,即使垃圾收集为您做了很多工作,您也应该摆脱对已完成对象的引用。否则他们仍然有一个根,他们不会被垃圾回收。

回答by Joshua

Watch that you remove any event handlers that you use. In .NET, they are the most common cause of leaked memory.

注意您删除了您使用的所有事件处理程序。在 .NET 中,它们是导致内存泄漏的最常见原因。

回答by Jon B

Having a basic understanding of how the garbage collectorworks will help you avoid abusing memory. For example, if you are keeping a reference to an object you no longer need, the gc won't be able to collect it.

垃圾收集器的工作原理有一个基本的了解将帮助您避免滥用内存。例如,如果您保留对不再需要的对象的引用,则 gc 将无法收集它。

Along the same lines, if you're storing data the the user enters, or data that is added over time, you should consider some kind of limitations so that your memory usage doesn't grow indefinitely.

同样,如果您要存储用户输入的数据或随时间添加的数据,您应该考虑某种限制,以便您的内存使用不会无限期地增长。

回答by hacken

I know some people are going to advise garbage collection as the solution. But there are lots of cases where garbage collection doesn't give you the results that you expect. It is easy to end up holding on to a stray reference which prevents whole chains of memory from being freed. Readabout how this torpedoed a DARPA Grand Challenge entry. You can argue these aren't memory leaks but if the program expects that memory to be freed it is still a problem. Just like in C programming, after a couple of months you get the hang of how to make sure you don't leave unwanted references behind.

我知道有些人会建议垃圾收集作为解决方案。但是在很多情况下,垃圾收集不会给您预期的结果。很容易最终持有一个杂散引用,从而阻止整个内存链被释放。阅读有关这如何破坏 DARPA 大挑战条目的信息。您可以争辩说这些不是内存泄漏,但如果程序期望内存被释放,它仍然是一个问题。就像在 C 编程中一样,几个月后您就会掌握如何确保不留下不需要的引用的窍门。

回答by Marc Charbonneau

I've ran into issues where an object (Ping) implemented Dispose() twice, by implementing the IDisposable interface and inheriting it at the same time. The inherited method did nothing, and as a result you had to cast the object to IDisposable when calling Dispose() or it would leak memory. Here's a post I wrote a few years agowith more detail.

我遇到了对象 (Ping) 通过实现 IDisposable 接口并同时继承它两次实现 Dispose() 的问题。继承的方法什么也没做,因此您必须在调用 Dispose() 时将对象强制转换为 IDisposable,否则会泄漏内存。这是我几年前写的一篇更详细的文章。

回答by Fredrik M?rk

Most memory leaks that I have encountered in .NET has been related to using COM objects and not releasing them properly. As soon as I see a reference to a COM object, I think "memory leak".

我在 .NET 中遇到的大多数内存泄漏都与使用 COM 对象和未正确释放它们有关。一旦我看到对 COM 对象的引用,我就会想到“内存泄漏”。

回答by Dmitri Kouminov

Use "using" keyword to automatically call Dispose() method of IDisposable object.
For any COM interop you have to manually release all resources.

使用“using”关键字自动调用IDisposable对象的Dispose()方法。
对于任何 COM 互操作,您都必须手动释放所有资源。

回答by Bob

  1. Wrap anything which is disposable in a using construct.
  2. Avoid COM objects.
  3. Check to see that all event hanlders are being removed properly.
  4. Check to see that all data bindings are being removed properly.
  5. Keep it simple
  1. 将任何一次性的东西都包裹在 using 结构中。
  2. 避免 COM 对象。
  3. 检查所有事件处理程序是否被正确删除。
  4. 检查所有数据绑定是否被正确删除。
  5. 把事情简单化

If your application logic is getting needlessly complex, you might start ending up with memory leaks. If you keep your classes small and follow general coding practices you probably won't run into any memory leaks with managed code. It is possible, but not as likely as it use to be.

如果您的应用程序逻辑变得不必要地复杂,您可能会开始出现内存泄漏。如果你保持你的类很小并遵循一般的编码实践,你可能不会遇到托管代码的任何内存泄漏。这是可能的,但不像以前那样可能。

If you suspect a memory leak, use a profiler to see if any objects are being kept around longer than needed.

如果您怀疑内存泄漏,请使用分析器查看是否有任何对象的保留时间超过了所需时间。

The last time I ran into a serious memory leak was .NET 1.1, it turned out there was a bug in the framework.

我上次遇到严重内存泄漏是在 .NET 1.1 上,结果发现框架中存在错误。