简体   繁体   English

如何在C#中跟踪内存分配

[英]How to trace memory allocation in C#

Are there any methods to trace how much memory is allocated, de-allocated and retrieved by GC for a particular module in C# .net ? 是否有任何方法可以跟踪GC为C#.net中的特定模块分配,取消分配和检索的内存量?

I want to trace out the possible memmory leaks in my module. 我想找出模块中可能的内存泄漏。 I am getting occasional System out of memory exceptions in production. 我在生产中偶尔遇到系统内存不足异常。

You should use a memory profiler to profile memory allocations. 您应该使用内存探查器来探查内存分配。

I've used JetBrains dotTrace , which has a nice mode of taking two snapshots at different times and showing which objects were allocated but not collected between those two snapshots. 我使用了JetBrains dotTrace ,它具有一种很好的模式,可以在不同时间拍摄两个快照,并显示在这两个快照之间分配了哪些对象但未收集哪些对象。 Allows for easy finding for memory leaks, where you keep allocating new instances and not collect them. 便于查找内存泄漏,您可以在其中分配新实例而不收集它们。

To view the difference between two application memory states, you can mark the start and the end of a time interval, then capture a difference snapshot which shows how much memory was allocated and released during the marked time interval. 要查看两个应用程序内存状态之间的差异,可以标记时间间隔的开始和结束,然后捕获差异快照,该快照显示在标记的时间间隔内分配和释放了多少内存。 The view can be filtered to show only live, new, or dead objects, or the difference between new and dead objects. 可以过滤视图以仅显示活动对象,新对象或无效对象,或显示新对象和无效对象之间的差异。

A memory profiler is a good idea. 内存分析器是一个好主意。 You can also get a rough sketch using the PerformanceCounters See the msdn . 你也可以使用它来获取草图PerformanceCounters参见MSDN You could then gather some stats on your prod environment if it's hard to reproduce locally. 如果很难在本地复制,则可以在产品环境中收集一些统计信息。

you can try .NET Memory Allocation Profiling with Visual Studio. 您可以尝试使用Visual Studio进行.NET内存分配分析。 try this msdn article to show you how http://blogs.msdn.com/b/dotnet/archive/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012.aspx . 试试这篇msdn文章,向您展示如何http://blogs.msdn.com/b/dotnet/archive/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012.aspx About 1/3 of the way through the article it shows how to Run the .NET memory allocation profiler. 在本文的大约1/3中,它显示了如何运行.NET内存分配分析器。

JetBrains, as mentioned, as well as .NET Memory profiler has helped me several times. 如前所述,JetBrains以及.NET Memory Profiler已经帮助了我多次。 If you have a memory leakage problem in WPF there are some good advice in this post (old but a lot is still valid): 如果您在WPF中存在内存泄漏问题,则本文中有一些不错的建议(旧的但很多仍然有效):

http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM