0

Is there a way to retrieve the total amount of native memory usage from a running C# application (either from within C# or an external CLI tool)? Something equivalent to the output of the non heap sections in jcmd's VM.native_memory?

I know about GCMemoryInfo.PinnedObjectsCount but that is only about the object count, not the size.

The intent is to publish it as a metric that can be tracked (i.e. not using complex debugging like Visual Studio, WinDbg or equivalents).

EDIT: I would be happy with the total amount of unmanaged memory, but something more granular like jcmd's output would be even better. Main goal is to track down native memory allocations via calls like Marshal.AllocHGlobal.

andresp
  • 1,624
  • 19
  • 31
  • Although this is not targeted at C#, the information given will apply, you just need to translate some of it. https://stackoverflow.com/questions/1476018/how-to-know-the-cpu-and-memory-usage-of-a-process-with-wmi – Neil Aug 15 '23 at 10:12

2 Answers2

0

Take a look into PerformanceCounter class.

Please, notice that It only works on Windows OS. In the previous project we needed to implement it on MacOs, but looks like because of different OS it throws OSException.

AVTUNEY
  • 923
  • 6
  • 11
0

There isn't really a single value for "native memory". It is a bit more complex than that. A good starting point is this series: https://techcommunity.microsoft.com/t5/windows-blog-archive/pushing-the-limits-of-windows-virtual-memory/ba-p/723750

The Process class exposes the different Windows memory stats. See https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=net-7.0

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • I would be happy with the total amount of unmanaged memory, but something more granular like jcmd's output would be even better. Main goal is to track down native memory allocations via calls like Marshal.AllocHGlobal. I will update my answer to make it clearer. – andresp Aug 15 '23 at 11:33
  • @andresp I am not aware of a direct way of doing that. Perhaps you could setup a hook using `iCorProfiler` and monitor the allocations that way. – Brian Rasmussen Aug 15 '23 at 11:43