有没有办法检索 C# 应用程序的当前内存使用情况?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/461139/
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
Is there a way to retrieve a C# app's current memory usage?
提问by Jeremy
I am automating some profiling tasks and want to log heap space and generation sizes real-time. The profiling APIseems awfully complicated for what I need, and it seems to listen in on individual allocations and collections, which isn't that important to me. Profiling tools are a great help of course, but I was looking for a more flexible, programmable interface.
我正在自动化一些分析任务,并希望实时记录堆空间和生成大小。该分析API看起来太过复杂,我需要什么,它似乎偷听个人分配和收藏,这是不是对我很重要。分析工具当然有很大帮助,但我一直在寻找更灵活、可编程的界面。
采纳答案by Mehrdad Afshari
The term 'current memory usage' is a little loosely defined. Do you mean the working set? Whatever it means, you can use different properties such as VirtualMemorySize
, WorkingSet
, PrivateMemorySize
, etc. from the process class to retrieve it.
术语“当前内存使用情况”的定义有点松散。你是说工作集吗?不管这意味着,你可以使用不同的属性,如VirtualMemorySize
,WorkingSet
,PrivateMemorySize
,等从工艺类进行检索。
long workingSet = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
回答by Brian Rasmussen
There are performance counters for a lot of this stuff and if you can't use Perfmon, you can access counters through the Diagnostics API.
有很多这些东西的性能计数器,如果你不能使用 Perfmon,你可以通过诊断 API 访问计数器。
回答by Valentin Heinitz
Once I had to find a memory leak in a legacy code, I came accross this solution: Start "tasklist" with appropriate parameters as a process and read the output either from stream or from file.
一旦我不得不在遗留代码中找到内存泄漏,我就遇到了这个解决方案:使用适当的参数启动“任务列表”作为一个进程,并从流或文件中读取输出。
e.g.
例如
tasklist /fi "IMAGENAME eq notepad++.exe" /FO CSV /NH
Output is:
输出是:
"notepad++.exe","7132","Console","1","21.004 K"
Not that elegant, but works in any programming language on Windows without additional dependences (C++/Qt in my case).
不是那么优雅,但可以在 Windows 上的任何编程语言中使用而无需额外的依赖(在我的情况下为 C++/Qt)。