简体   繁体   中英

Is there a way to retrieve a C# app's current memory usage?

I am automating some profiling tasks and want to log heap space and generation sizes real-time. The profiling API seems 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.

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.

long workingSet = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;

有许多这些东西的性能计数器,如果你不能使用Perfmon,你可以通过Diagnostics API访问计数器。

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.

eg

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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