Measuring the amount of memory in C # + Mono

I would like to measure how much of the system memory is available in my C# code. I believe this is done something like this:

 PerformanceCounter ramCounter = new PerformanceCounter( "Memory" , "Available MBytes" , true ); float availbleRam = ramCounter.NextValue(); 

Thing Mono does not have a category "Memmory" . I have listed the following categories:

 PerformanceCounterCategory[] cats = PerformanceCounterCategory.GetCategories(); string res = ""; foreach (PerformanceCounterCategory c in cats) { res += c.CategoryName + Environment.NewLine; } return res; 

And the closest category I found is "Mono Memory" , which does not have "Available MBytes" and continues to return 0 on NextValue calls. Here's a complete list of mono categories returns:

 Processor Process Mono Memory ASP.NET .NET CLR JIT .NET CLR Exceptions .NET CLR Memory .NET CLR Remoting .NET CLR Loading .NET CLR LocksAndThreads .NET CLR Interop .NET CLR Security Mono Threadpool Network Interface 

Does anyone know a way to measure available memory in C# + Mono + Ubuntu ?

[UPDATE]

I managed to do this in Ubuntu like this (using an external free program):

 long GetFreeMemorySize() { Regex ram_regex = new Regex(@"[^\s]+\s+\d+\s+(\d+)$"); ProcessStartInfo ram_psi = new ProcessStartInfo("free"); ram_psi.RedirectStandardOutput = true; ram_psi.RedirectStandardError = true; ram_psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; ram_psi.UseShellExecute = false; System.Diagnostics.Process free = System.Diagnostics.Process.Start(ram_psi); using (System.IO.StreamReader myOutput = free.StandardOutput) { string output = myOutput.ReadToEnd(); string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); lines[2] = lines[2].Trim(); Match match = ram_regex.Match(lines[2]); if (match.Success) { try { return Convert.ToInt64(match.Groups[1].Value); } catch (Exception) { return 0L; } } else { return 0L; } } } 

But the problem with this solution is that it works with Mono only if it is running on a Linux system. I would like to know if anyone can come up with a solution for Mono + Windows ?

+4
source share
1 answer
 Thread.Sleep(1000); 

Put this after the first call to "NextValue" (you can throw up the very first return value of NextValue) and follow it with your line:

 float availbleRam = ramCounter.NextValue(); 

Performance counters take time to measure before they can return results.

Confirmed this works on Windows with .net 4.5, not sure about Linux with Mono.

0
source

Source: https://habr.com/ru/post/1501277/


All Articles