CPU and Memory Usage in C#

using System;
using System.Management;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE NOT Name='_Total'");
                ManagementObjectSearcher searcher2 =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_OperatingSystem");
                for(int c=0; c<15; c++)
                {
                    for (var i = searcher.Get().GetEnumerator(); i.MoveNext();)
                    {
                        string ts = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fffffff");
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        Console.WriteLine("Core {0} running at {1} % on {2}", queryObj["Name"], queryObj["PercentProcessorTime"], ts);
                    }
                    for (var i = searcher2.Get().GetEnumerator(); i.MoveNext();)
                    {
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        double free = Double.Parse(queryObj["FreePhysicalMemory"].ToString());
                        double total = Double.Parse(queryObj["TotalVisibleMemorySize"].ToString());
                        Console.WriteLine("Amount used: {0} GB", (total - free)/(1024*1024));
                        Console.WriteLine("Percentage used: {0}%", Math.Round(((total - free) / total * 100), 2));
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadKey(true);
            }
            catch (ManagementException e)
            {
                Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

This example queries Windows Management Instrumentation (WMI) from C# to read CPU and memory usage. WMI exposes performance and hardware data through query classes such as Win32_Processor and Win32_OperatingSystem, which you read with System.Management.

It is a quick way to gather system metrics inside a .NET application without third party libraries. WMI is Windows only, so for cross platform needs consider the PerformanceCounter class or operating system specific APIs.

Comments

Popular posts from this blog

The 2026 AI Cheat Sheet: Best Tool for Every Task

[Solved] Error: No such keg: /usr/local/Cellar/gcc