c#利用PerformanceCounter进行网卡流量监控

本文介绍了如何利用C#的PerformanceCounter类来实现网卡流量的监控。包括两种方法:一是直接通过NextValue()计算下载速率,二是自定义类MyNetWorkMatchClass和MyNetWorkMonitor结合NextSample().RawValue来计算上传下载速率。
摘要由CSDN通过智能技术生成

PerformanceCounter基础知识:

在这里插入图片描述

参考

Performance Counter的使用

利用PerformanceCounter进行网卡流量监控

方法一:利用PerformanceCounter实例.NextValue()计算网卡下载速率
NextValue()使用注意(文章末尾)

namespace GPS222
{
   
    public partial class Form2 : Form
    {
   
        private PerformanceCounter mCounter;//当前计数器
        private void begin_n_Click(object sender, EventArgs e)
        {
   
              timer2_net.Interval = 1000;//。1秒一次timer2_Tick事件
              timer2_net.Enabled = true;
             //初始化Counter
             PerformanceCounterCategory pcCategory = new PerformanceCounterCategory("Network Interface");
             string[] iNames = pcCategory.GetInstanceNames();//此函数第一次执行特别耗时(不知道为什么)
             PerformanceCounter[] pCounters = pcCategory.GetCounters(iNames[1]);//iNames[0]为"ASIX AX88772C USB2.0 to Fast Ethernet Adapter";iNames[1]为"Intel[R] Ethernet Connection [7] I219-V"
             //给网络监控计数器赋值
             mCounter = pCounters[0];
             mCounter.NextValue();//初始值  
       }
       private void timer2_net_Tick(object sender, EventArgs e)
       {
                            
            double SpeedKbps = mCounter.NextValue() * 8 / 1000;
            if ((SpeedKbps / 1000) > 1)
            {
   
                SpeedSendToolLabel.Text = String.Format("{0:f1} Mbps", SpeedKbps / 1000); //得到该适配器的上传速度
            }
            else
            {
   
                SpeedSendToolLabel.Text = String.Format("{0:f1} Kbps", SpeedKbps); //得到该适配器的上传速度
            }
       }       

方法二(繁琐):自定义了两个类:MyNetWorkMatchClass和MyNetWorkMonitor,利用PerformanceCounter实例.NextSample().RawValue自行计算网卡上传下载速率(CaculateAndRefresh()函数)
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Collections;
using System.Timers;
using System.Diagnostics;//Stopwatch\PerformanceC
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值