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

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\PerformanceCounter



namespace WindowsFormsApplication2
{
    public partial class NetJiankongForm2 : Form
    {
        private MyNetWorkMatchClass[] m_MNWMadapters;
        private MyNetWorkMonitor monitor;
        public NetJiankongForm2()
        {
            InitializeComponent();
        }
        private void NetJiankongForm2_Load(object sender, EventArgs e)
        {
            monitor = new MyNetWorkMonitor();
            m_MNWMadapters = monitor.Adapters; //获得控制器MyNetWorkMonitor上所有计算机的适配器列表

            if (m_MNWMadapters.Length == 0)
            {
                listBox1.Enabled = false;
                MessageBox.Show("在计算机上没有找到网络适配器");
                return;
            }

            listBox1.Items.AddRange(m_MNWMadapters);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e) //选中其中一个适配器
        {
                monitor.StopMonitoring();
                monitor.StartMonitoring(m_MNWMadapters[listBox1.SelectedIndex]); //控制该适配器开始工作
                this.timer1.Start(); //计时开始
        }

        private void timer1_Tick(object sender, EventArgs e) //计时开始,用于每秒钟改变显示速度
        {

                MyNetWorkMatchClass adapter = m_MNWMadapters[listBox1.SelectedIndex]; //该适配器
                textBox_Down.Text = String.Format("{0:n} kbps", adapter.DownloadSpeedKbps); //得到该适配器的下载速度
                textBox_Up.Text = String.Format("{0:n} kbps", adapter.UploadSpeedKbps); //得到该适配器的上传速度
                
        } 
    }
    class MyNetWorkMonitor
    {
        private System.Timers.Timer Monitor_Timer; // 计时器事件执行每秒钟刷新值在适配器。
        private ArrayList m_AdaptersList; //该计算机的适配器列表。
        private ArrayList m_MonitoredAdapters; //目前控制的(需要Monitor的)适配器列表

    class MyNetWorkMonitor
    {
        private System.Timers.Timer Monitor_Timer; // 计时器事件执行每秒钟刷新值在适配器。
        private ArrayList m_AdaptersList; //该计算机的适配器列表。
        private ArrayList m_MonitoredAdapters; //目前控制的(需要Monitor的)适配器列表
        public MyNetWorkMonitor()
        {    
             m_AdaptersList = new ArrayList(); //用来保存获取到的计算机的适配器列表    
             m_MonitoredAdapters = new ArrayList(); //运行的有效的(需要Monitor的)适配器列表
            ShowNetAdapter(); //列举出安装在该计算机上面的适配器
            Monitor_Timer = new System.Timers.Timer(1000);
            Monitor_Timer.Elapsed += new ElapsedEventHandler(timer_ElapsedClick);//StartMonitoring方法中开启时钟
        }
        private void timer_ElapsedClick(object sender, ElapsedEventArgs e) //用于每秒钟刷新速度 
        {
            foreach (MyNetWorkMatchClass adapter in m_MonitoredAdapters) //每秒钟遍历有效的网络适配器
            {
                adapter.CaculateAndRefresh(); //刷新上传下载速度 
            }
        }
        private void ShowNetAdapter() //列举出安装在该计算机上面的适配器方法
        {
            PerformanceCounterCategory PCCCategory = new PerformanceCounterCategory("Network
Interface");
            string[] InstanceNames = PCCCategory.GetInstanceNames();
            foreach (string InstanceName in InstanceNames)
            {
                if (InstanceName == "MS TCP Loopback interface")//?
                    continue;
                // 创建一个实例Net workAdapter类别,并创建性能计数器它。
                MyNetWorkMatchClass myMNWMadapter = new MyNetWorkMatchClass(InstanceName);
                myMNWMadapter.m_Performance_Down = new PerformanceCounter("Network
Interface", "Bytes Received/sec", InstanceName);
                myMNWMadapter.m_Performance_Up= new PerformanceCounter("Network
Interface", "Bytes Sent/sec", InstanceName);               
                m_AdaptersList.Add(myMNWMadapter);
            }
        }
        public void StartMonitoring()//控制适配器开始工作(开启Monitor_Timer时钟)
        {
            if(m_AdaptersList.Count > 0)//鲁棒性(防崩溃)
            {
                foreach (MyNetWorkMatchClass myMNWMadapter in m_AdaptersList)
                    if(!m_MonitoredAdapters.Contains(myMNWMadapter))
                    {                       
                        m_MonitoredAdapters.Add(myMNWMadapter);
                        myMNWMadapter.Start();
                    }
                Monitor_Timer.Enabled = true;
            }       
        }       
        public void StartMonitoring(MyNetWorkMatchClass myMNWMadapter) //控制该适配器开始工作(开启Monitor_Timer时钟)
       {
            if(!m_MonitoredAdapters.Contains(myMNWMadapter))
            {               
                m_MonitoredAdapters.Add(myMNWMadapter);
                myMNWMadapter.Start(); //该适配器调用自己函数开始工作 
            }
            Monitor_Timer.Enabled = true;       
        }
       public void StopMonitoring()     
       {
            m_MonitoredAdapters.Clear();
            Monitor_Timer.Enabled = false;
       }
       public void StopMonitoring(MyNetWorkMatchClass adapter)
       {
            if(m_MonitoredAdapters.Contains(adapter))
               m_MonitoredAdapters.Remove(adapter);
            if(m_MonitoredAdapters.Count == 0)
               Monitor_Timer.Enabled = false;
       }
       public MyNetWorkMatchClass[] Adapters //该控制类所控制的找出所有适配器的适配器列表
       {
            get
            {
                return (MyNetWorkMatchClass[])m_AdaptersList.ToArray(typeof(MyNetWorkMatchClass));
            }
       }
   }
   class MyNetWorkMatchClass
   {
       public override string ToString()
       {
            return m_strMatchName;
       }
       public string strMatchName//"ASIX AX88772C USB2.0 to Fast Ethernet Adapter"或"Intel[R] Ethernet Connection [7] I219-V"
       {
            get
            {
                return m_strMatchName;
            }
       }
       public long DownloadSpeed
       {
            get
            {
                return m_lDownLoadSpeed;
            }       
       }
       public long UploadSpeed
       {
            get
            {
                return m_lUpLoadSpeed;
            }
       }
       public double DownloadSpeedKbps
       {
            get
            {
                return this.m_lDownLoadSpeed*8/ 1000.0;//理论上应除以1024,但实际除以1000才与性能管理器中所显示吞吐量一致
            }
       } 
       public double UploadSpeedKbps
       {
            get
            {
                return this.m_lUpLoadSpeed*8 /1000.0;//理论上应除以1024,但实际除以1000才与性能管理器中所显示吞吐量一致
            }
       }
       private long m_lDownLoadNetValues1; //当前的下载速度,***字节***计算(须*8变为bit才与性能管理器中所显示吞吐量一致)
       private long m_lUploadNetValues1; //当前的上传速度
       private long m_lDownLoadNetValues2; //一秒前的下载速度,***字节***计算(须*8变为bit才与性能管理器中所显示吞吐量一致)
       private long m_lUploadNetValues2; //一秒前的上传速度
       private string m_strMatchName; //此适配器的名字
       internal PerformanceCounter m_Performance_Down; //控制下载速度的流量计算中心
       internal PerformanceCounter m_Performance_Up; // //控制上传速度的流量计算中心
       private long m_lDownLoadSpeed; //每秒钟下载速度
       private long m_lUpLoadSpeed; //每秒钟上传速度
       public MyNetWorkMatchClass(string strComputerNetName)
       {
            m_lDownLoadNetValues1 = 0;
            m_strMatchName =strComputerNetName;
            m_lUploadNetValues1 = 0;
            m_lDownLoadNetValues2 = 0;
            m_lUploadNetValues2 = 0;
       }
       //该适配器准备控制的方法函数
       public void Start()
       {
            m_lUploadNetValues1 =m_Performance_Up.NextSample().RawValue;
            m_lDownLoadNetValues1 =m_Performance_Down.NextSample().RawValue;
       }
       public void CaculateAndRefresh() //计算速度
       {
            m_lDownLoadNetValues2 =m_Performance_Down.NextSample().RawValue;
            m_lUploadNetValues2 =m_Performance_Up.NextSample().RawValue;
            m_lDownLoadSpeed =m_lDownLoadNetValues2 - m_lDownLoadNetValues1;
            m_lUpLoadSpeed = m_lUploadNetValues2- m_lUploadNetValues1;
            m_lDownLoadNetValues1 =m_lDownLoadNetValues2;
            m_lUploadNetValues1 =m_lUploadNetValues2;
       }
   }
}

参考

求助:用c#怎么测网卡的吞吐量,急用
C#流量监控源代码
C# 利用性能计数器监控网络状态

你可能感兴趣的:(c#利用PerformanceCounter进行网卡流量监控)