1

Is there any method in C# to have the current amount of memory used and how much is available, without needing to loop over all processes and add each workingset64 value?

Devang
  • 69
  • 1
  • 3
  • do you mean resource usage of current process, or other processes? – Lei Yang Mar 15 '22 at 06:57
  • of all the processes running at the moment, say they are using 14GB of RAM, so how do i get this value in my code – Devang Mar 15 '22 at 07:04
  • 1
    Does this answer your question? [How to get the size of available system memory?](https://stackoverflow.com/questions/3296211/how-to-get-the-size-of-available-system-memory) – Lei Yang Mar 15 '22 at 07:08
  • No, it doesn't :( I need something specific to .netcore as my app is cross-platform – Devang Mar 15 '22 at 07:12
  • 1
    how about [How to get memory available or used in C# .net core / .net standard](https://stackoverflow.com/a/45268831/1518100) – Lei Yang Mar 15 '22 at 07:14
  • 3
    You cannot get that information in pure .NET Core yet. https://github.com/dotnet/runtime/issues/22948 - If you just want to find out how much memory all processes are using, you can enumerate all Process objects and tally up information. It won't tell you how much memory is available in the computer, however. – Lasse V. Karlsen Mar 15 '22 at 09:14
  • @LeiYang Yeah that is what can be done currently but as Lasse V. Karlsen mentioned we need to do it for all processes, hence a loop. Thanks for sharing both of you. – Devang Mar 15 '22 at 09:32
  • 3
    Seems someone has created a project for this that maybe can tend to your needs. https://github.com/Jinjinov/Hardware.Info – Ole Haugset Mar 15 '22 at 09:33

1 Answers1

2

Well, you could do this:

public class MemoryMetrics
{
    public double Total;
    public double Used;
    public double Free;
}

public class MemoryMetricsService : IMemoryMetricsService
{
    public IRuntimeInformationService RuntimeInformationService { get; set; }
    public MemoryMetricsService(IRuntimeInformationService runtimeInformationService)
    {
        this.RuntimeInformationService = runtimeInformationService;
    }
    public MemoryMetrics GetMetrics()
    {
        if (RuntimeInformationService.IsUnix())
        {
            return GetUnixMetrics();
        }

        return GetWindowsMetrics();
    }

    private MemoryMetrics GetWindowsMetrics()
    {
        var output = "";

        var info = new ProcessStartInfo();
        info.FileName = "wmic";
        info.Arguments = "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value";
        info.RedirectStandardOutput = true;

        using (var process = Process.Start(info))
        {
            output = process.StandardOutput.ReadToEnd();
        }

        var lines = output.Trim().Split("\n");
        var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
        var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);

        var metrics = new MemoryMetrics();
        metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
        metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
        metrics.Used = metrics.Total - metrics.Free;

        return metrics;
    }

    private MemoryMetrics GetUnixMetrics()
    {
        var output = "";

        var info = new ProcessStartInfo("free -m");
        info.FileName = "/bin/bash";
        info.Arguments = "-c \"free -m\"";
        info.RedirectStandardOutput = true;

        using (var process = Process.Start(info))
        {
            output = process.StandardOutput.ReadToEnd();
            Console.WriteLine(output);
        }

        var lines = output.Split("\n");
        var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);

        var metrics = new MemoryMetrics();
        metrics.Total = double.Parse(memory[1]);
        metrics.Used = double.Parse(memory[2]);
        metrics.Free = double.Parse(memory[3]);

        return metrics;
    }
}

as for IRuntimeInformationService:

using System.Runtime.InteropServices;
public class RuntimeInformationService : IRuntimeInformationService
{
    public OSPlatform GetOsPlatform()
    {
        if(RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return OSPlatform.OSX;
        if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return OSPlatform.Linux;
        if(RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return OSPlatform.FreeBSD;
        if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return OSPlatform.Windows;

        return OSPlatform.Create("Unknown");
    }

    public bool IsUnix()
    {
        var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ||
                     RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

        return isUnix;
    }
    
    public bool IsWindows()
    {
        return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
    }
    
    public bool IsLinux()
    {
        return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
    }
    
    public bool IsFreeBSD()
    {
        return RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD);
    }
    
    public bool IsOSX()
    {
        return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
    }
    
    public string GetRuntimeIdentifier()
    {
        return RuntimeInformation.RuntimeIdentifier;
    }
    
    public Architecture GetProcessArchitecture()
    {
        return RuntimeInformation.ProcessArchitecture;
    }

    public Architecture GetOSArchitecture()
    {
        return RuntimeInformation.OSArchitecture;
    }
    
    public string GetOSDescription()
    {
        return RuntimeInformation.OSDescription;
    }       
    public string GetFrameworkDescription()
    {
        return RuntimeInformation.FrameworkDescription;
    }
}
Djordje Nedovic
  • 559
  • 8
  • 20
Daniel Lozano
  • 511
  • 5
  • 15