当前位置: 代码网 > it编程>编程语言>Asp.net > C#实时查看硬件使用率的实现方案

C#实时查看硬件使用率的实现方案

2026年05月12日 Asp.net 我要评论
一、整体架构┌─────────────────────────────────────────────────────────────┐│ 硬件资源监控系统

一、整体架构

┌─────────────────────────────────────────────────────────────┐
│                    硬件资源监控系统                         │
├─────────────────────────────────────────────────────────────┤
│  数据采集层   │  业务逻辑层   │  展示层        │  告警层    │
│               │               │                │            │
│  • performancecounter        │  • 数据缓存    │  • winforms │
│  • wmi (managementobject)   │  • 定时采样    │  • wpf      │
│  • system.diagnostics       │  • 历史记录    │  • 上位机   │
│  • snmp / ssh (远程)        │  • 阈值判断    │  • web api  │
└─────────────────────────────────────────────────────────────┘

二、方案一:本机实时监控

适合:上位机、工业pc、边缘网关

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 实时显示

3.1 mainwindow.xaml

<window x:class="hardwaremonitor.mainwindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        title="硬件实时监控" 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="内存使用" 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# 实时查看 硬件使用率(cpu/内存/硬盘等) www.youwenfan.com/contentcsu/62418.html

四、方案三:远程设备监控

4.1 通过 wmi 监控远程 windows 设备

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 上位机)

// 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#实时查看硬件使用率的实现方案的详细内容,更多关于c#实时查看硬件使用率的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com