最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實(shí)時(shí)查看硬件使用率的實(shí)現(xiàn)方案

 更新時(shí)間:2026年05月12日 09:24:40   作者:yong9990  
文章主要介紹了如何通過C#進(jìn)行硬件監(jiān)控,包括實(shí)時(shí)監(jiān)控本機(jī)硬件使用情況(CPU、內(nèi)存、硬盤等),使用WPF進(jìn)行實(shí)時(shí)顯示,以及通過WMI監(jiān)控遠(yuǎn)程Windows設(shè)備,同時(shí),還提到了適用于Linux/ARM/嵌入式系統(tǒng)的監(jiān)控方案,需要的朋友可以參考下

一、整體架構(gòu)

┌─────────────────────────────────────────────────────────────┐
│                    硬件資源監(jiān)控系統(tǒng)                         │
├─────────────────────────────────────────────────────────────┤
│  數(shù)據(jù)采集層   │  業(yè)務(wù)邏輯層   │  展示層        │  告警層    │
│               │               │                │            │
│  ? PerformanceCounter        │  ? 數(shù)據(jù)緩存    │  ? WinForms │
│  ? WMI (ManagementObject)   │  ? 定時(shí)采樣    │  ? WPF      │
│  ? System.Diagnostics       │  ? 歷史記錄    │  ? 上位機(jī)   │
│  ? SNMP / SSH (遠(yuǎn)程)        │  ? 閾值判斷    │  ? Web API  │
└─────────────────────────────────────────────────────────────┘

二、方案一:本機(jī)實(shí)時(shí)監(jiān)控

適合:上位機(jī)、工業(yè)PC、邊緣網(wǎng)關(guān)

2.1 核心類(HardwareMonitor.cs)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Threading;
namespace HardwareMonitor
{
    public class HardwareMonitor
    {
        private readonly Timer _timer;
        private readonly int _intervalMs;
        public delegate void HardwareDataHandler(HardwareData data);
        public event HardwareDataHandler OnDataUpdated;
        public HardwareMonitor(int intervalMs = 1000)
        {
            _intervalMs = intervalMs;
            _timer = new Timer(Collect, null, Timeout.Infinite, Timeout.Infinite);
        }
        public void Start() => _timer.Change(0, _intervalMs);
        public void Stop() => _timer.Change(Timeout.Infinite, Timeout.Infinite);
        private void Collect(object state)
        {
            var data = new HardwareData
            {
                CpuUsage = GetCpuUsage(),
                MemoryUsedMb = GetMemoryUsed(),
                MemoryTotalMb = GetMemoryTotal(),
                DiskUsage = GetDiskUsage(),
                NetworkSentKBps = GetNetworkSent(),
                NetworkReceivedKBps = GetNetworkReceived(),
                Temperature = GetCpuTemperature()
            };
            OnDataUpdated?.Invoke(data);
        }
        #region CPU
        private float GetCpuUsage()
        {
            using var cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            cpu.NextValue();
            Thread.Sleep(100);
            return cpu.NextValue();
        }
        #endregion
        #region Memory
        private float GetMemoryUsed()
        {
            using var mem = new PerformanceCounter("Memory", "Committed Bytes");
            return mem.NextValue() / 1024 / 1024;
        }
        private float GetMemoryTotal()
        {
            using var mem = new PerformanceCounter("Memory", "Commit Limit");
            return mem.NextValue() / 1024 / 1024;
        }
        #endregion
        #region Disk
        private float GetDiskUsage()
        {
            using var disk = new PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total");
            disk.NextValue();
            Thread.Sleep(100);
            return disk.NextValue();
        }
        #endregion
        #region Network
        private float GetNetworkSent()
        {
            using var net = new PerformanceCounter("Network Interface", "Bytes Sent/sec", GetNetworkCard());
            return net.NextValue() / 1024;
        }
        private float GetNetworkReceived()
        {
            using var net = new PerformanceCounter("Network Interface", "Bytes Received/sec", GetNetworkCard());
            return net.NextValue() / 1024;
        }
        private string GetNetworkCard()
        {
            using var searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_NetworkAdapter WHERE NetEnabled = true");
            foreach (ManagementObject obj in searcher.Get())
                return obj["Name"].ToString();
            return "";
        }
        #endregion
        #region Temperature (WMI)
        private float GetCpuTemperature()
        {
            try
            {
                using var searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT CurrentTemperature FROM MSAcpi_ThermalZoneTemperature");
                foreach (ManagementObject obj in searcher.Get())
                {
                    var temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
                    return (float)(temp / 10.0 - 273.15); // Kelvin → Celsius
                }
            }
            catch { }
            return 0;
        }
        #endregion
    }
    public class HardwareData
    {
        public float CpuUsage { get; set; }
        public float MemoryUsedMb { get; set; }
        public float MemoryTotalMb { get; set; }
        public float DiskUsage { get; set; }
        public float NetworkSentKBps { get; set; }
        public float NetworkReceivedKBps { get; set; }
        public float Temperature { get; set; }
        public override string ToString()
        {
            return $"CPU:{CpuUsage:F1}%  MEM:{MemoryUsedMb:F0}/{MemoryTotalMb:F0}MB  DISK:{DiskUsage:F1}%  TEMP:{Temperature:F1}℃";
        }
    }
}

三、方案二:WPF 實(shí)時(shí)顯示

3.1 MainWindow.xaml

<Window x:Class="HardwareMonitor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="硬件實(shí)時(shí)監(jiān)控" Height="320" Width="400">
    <StackPanel Margin="20">
        <TextBlock Text="CPU 使用率" FontWeight="Bold"/>
        <ProgressBar x:Name="CpuBar" Height="20" Maximum="100"/>
        <TextBlock x:Name="CpuText"/>
        <TextBlock Text="內(nèi)存使用" FontWeight="Bold" Margin="0,10,0,0"/>
        <ProgressBar x:Name="MemBar" Height="20" Maximum="100"/>
        <TextBlock x:Name="MemText"/>
        <TextBlock Text="硬盤使用" FontWeight="Bold" Margin="0,10,0,0"/>
        <ProgressBar x:Name="DiskBar" Height="20" Maximum="100"/>
        <TextBlock Text="CPU 溫度" FontWeight="Bold" Margin="0,10,0,0"/>
        <TextBlock x:Name="TempText" FontSize="16" Foreground="Red"/>
    </StackPanel>
</Window>

3.2 MainWindow.xaml.cs

using System.Windows;

namespace HardwareMonitor
{
    public partial class MainWindow : Window
    {
        private readonly HardwareMonitor _monitor;

        public MainWindow()
        {
            InitializeComponent();
            _monitor = new HardwareMonitor(1000);
            _monitor.OnDataUpdated += UpdateUI;
            _monitor.Start();
        }

        private void UpdateUI(HardwareData data)
        {
            Dispatcher.Invoke(() =>
            {
                CpuBar.Value = data.CpuUsage;
                CpuText.Text = $"{data.CpuUsage:F1}%";

                MemBar.Value = data.MemoryUsedMb / data.MemoryTotalMb * 100;
                MemText.Text = $"{data.MemoryUsedMb:F0} MB / {data.MemoryTotalMb:F0} MB";

                DiskBar.Value = data.DiskUsage;
                TempText.Text = $"{data.Temperature:F1} ℃";
            });
        }
    }
}

參考代碼 C# 實(shí)時(shí)查看 硬件使用率(CPU/內(nèi)存/硬盤等) www.youwenfan.com/contentcsu/62418.html

四、方案三:遠(yuǎn)程設(shè)備監(jiān)控

4.1 通過 WMI 監(jiān)控遠(yuǎn)程 Windows 設(shè)備

public static float GetRemoteCpuUsage(string ip, string user, string pwd)
{
    var options = new ConnectionOptions
    {
        Username = user,
        Password = pwd,
        Impersonation = ImpersonationLevel.Impersonate
    };

    var scope = new ManagementScope($"\\\\{ip}\\root\\cimv2", options);
    scope.Connect();

    using var searcher = new ManagementObjectSearcher(
        scope, new ObjectQuery("SELECT LoadPercentage FROM Win32_Processor"));

    foreach (ManagementObject obj in searcher.Get())
        return Convert.ToSingle(obj["LoadPercentage"]);

    return 0;
}

五、Linux / ARM / 嵌入式(STM32 上位機(jī))

// Linux
cat /proc/cpuinfo
cat /proc/meminfo
df -h
public static float GetLinuxCpuUsage()
{
    var cpu = File.ReadAllText("/proc/stat").Split('\n')[0];
    return ParseCpu(cpu);
}

以上就是C#實(shí)時(shí)查看硬件使用率的實(shí)現(xiàn)方案的詳細(xì)內(nèi)容,更多關(guān)于C#實(shí)時(shí)查看硬件使用率的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

永泰县| 永嘉县| 任丘市| 衡山县| 华阴市| 湖口县| 东宁县| 芜湖县| 青冈县| 收藏| 桑日县| 钦州市| 大关县| 玉门市| 南丹县| 吴忠市| 大埔区| 儋州市| 花垣县| 鄂尔多斯市| 来宾市| 祁门县| 比如县| 锡林浩特市| 呼图壁县| 隆回县| 宝坻区| 永州市| 阜康市| 宜丰县| 呼伦贝尔市| 镇原县| 鞍山市| 察哈| 四平市| 潍坊市| 姚安县| 平定县| 桐乡市| 崇左市| 恩平市|