C# 利用性能計數器監控網絡狀態


本例是利用C#中的性能計數器(PerformanceCounter)監控網絡的狀態,並能夠直觀的展現出來。本文僅供學習分享使用,如有不足之處,還請指正。

涉及知識點:

  • PerformanceCounter,表示 Windows NT 性能計數器組件。NextValue() 即獲取計數器樣本並為其返回計算所得值。
  • PerformanceCounterCategory 表示性能對象,它定義性能計數器的類別。通過這兩個即可得到計數器的信息。
  • Chart 圖表,VS自帶的Chart圖表,大大簡化了對圖表的開發。關於Chart,此前已有例子說明
  • Queue 隊列表示對象的先進先出集合。關於Queue此前已有例子說明
  • TreeView 顯示標記項的分層集合,每個標記項用一個 System.Windows.Forms.TreeNode 來表示。即VS自帶的樹狀菜單
  • Timer 實現按用戶定義的時間間隔引發事件的計時器。此計時器最宜用於 Windows 窗體應用程序中,並且必須在窗口中使用。定時刷新計數器中的值。

效果圖

如下圖所示:

關於可用的計數器列表【計數器有很多,一級菜單是計數器的類別,二級菜單是計數器InstanceName,三級菜單是計數器名稱】,如下圖所示:

核心代碼

代碼如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using System.Windows.Forms.DataVisualization.Charting;
 10 using System.Diagnostics;
 11 
 12 namespace DemoSharp
 13 {
 14     public partial class NetworkMonitor : Form
 15     {
 16         private PerformanceCounter mCounter;//當前計數器
 17 
 18         private Queue<double> dataQueue = new Queue<double>(100);//初始化隊列
 19 
 20         public NetworkMonitor()
 21         {
 22             InitializeComponent();
 23             InitCounterCategory();
 24             InitChart();
 25         }
 26 
 27         /// <summary>
 28         /// 初始化計數器信息
 29         /// </summary>
 30         private void InitCounterCategory() {
 31             //獲取所有的計數器類別
 32             var counterCategories = PerformanceCounterCategory.GetCategories().OrderBy(p=>p.CategoryName);
 33             int i=0;
 34             foreach (var counterCategory in counterCategories) {
 35                 //屬於線程級別的不顯示
 36                 if (counterCategory.CategoryName == "Thread") {
 37                     continue;
 38                 }
 39                 //將信息綁定的TreeView上
 40                 this.tvCategory.CheckBoxes = true;
 41                 this.tvCategory.Nodes.Add(counterCategory.CategoryName);
 42                 string[] instanceNames = counterCategory.GetInstanceNames();
 43                 int j = 0;
 44                 foreach (var instanceName in instanceNames) {
 45                     this.tvCategory.Nodes[i].Nodes.Add(instanceName);
 46                     var counters = counterCategory.GetCounters(instanceName).Select(p=>string.Format("{0}",p.CounterName));
 47                     int k = 0;
 48                     foreach (var counter in counters) {
 49                         this.tvCategory.Nodes[i].Nodes[j].Nodes.Add(counter);
 50                         k++;
 51                     }
 52                     j++;
 53                 }
 54                 i++;
 55             }
 56             //初始化Counter
 57             PerformanceCounterCategory pcCategory = new PerformanceCounterCategory("Network Interface");
 58             string[] iNames = pcCategory.GetInstanceNames();
 59             PerformanceCounter[] pCounters = pcCategory.GetCounters(iNames[0]);
 60             //給網絡監控計數器賦值
 61             mCounter = pCounters[0];
 62             mCounter.NextValue();//初始值
 63         }
 64 
 65          //<summary>
 66          //初始化圖表
 67          //</summary>
 68         private void InitChart()
 69         {
 70             //定義圖表區域
 71             this.chart1.ChartAreas.Clear();
 72             ChartArea chartArea1 = new ChartArea("C1");
 73             this.chart1.ChartAreas.Add(chartArea1);
 74             //定義存儲和顯示點的容器
 75             this.chart1.Series.Clear();
 76             Series series1 = new Series("S1");
 77             series1.ChartArea = "C1";
 78             this.chart1.Series.Add(series1);
 79             //設置圖表顯示樣式
 80             this.chart1.ChartAreas[0].AxisY.ArrowStyle = AxisArrowStyle.SharpTriangle;
 81             this.chart1.ChartAreas[0].AxisY.Title = "Kkbps";//坐標軸的標題
 82             this.chart1.ChartAreas[0].AxisY.TextOrientation = TextOrientation.Rotated270;
 83             this.chart1.ChartAreas[0].AxisY.Minimum = 0;
 84             this.chart1.ChartAreas[0].AxisY.Maximum = 50;
 85             this.chart1.ChartAreas[0].AxisY.Interval = 5;
 86             this.chart1.ChartAreas[0].AxisX.Interval = 5;
 87             this.chart1.ChartAreas[0].AxisX.ArrowStyle = AxisArrowStyle.SharpTriangle;
 88             this.chart1.ChartAreas[0].AxisX.Title = "Sec";
 89             this.chart1.ChartAreas[0].AxisX.TextOrientation = TextOrientation.Horizontal;
 90             this.chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Silver;
 91             this.chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Silver;
 92             //設置標題
 93             this.chart1.Titles.Clear();
 94             this.chart1.Titles.Add("S01");
 95             this.chart1.Titles[0].Text = "XXX網絡監控顯示";
 96             this.chart1.Titles[0].ForeColor = Color.RoyalBlue;
 97             this.chart1.Titles[0].Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
 98             //設置圖表顯示樣式
 99             this.chart1.Series[0].Color = Color.LightGreen;
100             this.chart1.Series[0].ChartType = SeriesChartType.Area;//圖表形狀
101             this.chart1.Series[0].Points.Clear();
102         }
103 
104         /// <summary>
105         /// 啟動定時器
106         /// </summary>
107         /// <param name="sender"></param>
108         /// <param name="e"></param>
109         private void btnStart_Click(object sender, EventArgs e)
110         {
111             this.timer1.Start();
112             
113         }
114 
115         /// <summary>
116         /// 停止定時器
117         /// </summary>
118         /// <param name="sender"></param>
119         /// <param name="e"></param>
120         private void btnStop_Click(object sender, EventArgs e)
121         {
122             this.timer1.Stop();
123         }
124 
125         /// <summary>
126         /// 定時執行函數
127         /// </summary>
128         /// <param name="sender"></param>
129         /// <param name="e"></param>
130         private void timer1_Tick(object sender, EventArgs e)
131         {
132             UpdateQueueValue();
133             this.chart1.Series[0].Points.Clear();
134             if (dataQueue.Max() > this.chart1.ChartAreas[0].AxisY.Maximum) {
135                 this.chart1.ChartAreas[0].AxisY.Maximum = Math.Ceiling(dataQueue.Max() / 10) * 10;
136                 this.chart1.ChartAreas[0].AxisY.Interval = this.chart1.ChartAreas[0].AxisY.Maximum / 10;
137             }
138             for (int i = 0; i < dataQueue.Count; i++)
139             {
140                 this.chart1.Series[0].Points.AddXY((i + 1), dataQueue.ElementAt(i));
141             }
142         }
143 
144          //更新隊列中的值
145         private void UpdateQueueValue()
146         {
147 
148             if (dataQueue.Count > 100)
149             {
150                 dataQueue.Dequeue();
151             }
152             //獲取的值就Byte/s 所以要除以1024
153             dataQueue.Enqueue(mCounter.NextValue() / (1024));
154 
155         }
156 
157         /// <summary>
158         /// 當選中復選框時發生
159         /// </summary>
160         /// <param name="sender"></param>
161         /// <param name="e"></param>
162         private void tvCategory_AfterCheck(object sender, TreeViewEventArgs e)
163         {
164             bool flag = e.Node.Checked;//取得選中狀態,所有子節點的狀態保持一致
165             CheckedStated(e.Node.Nodes, flag);
166         }
167 
168         /// <summary>
169         /// 采用遞歸方法修改節點的選中狀態
170         /// </summary>
171         /// <param name="nodes"></param>
172         /// <param name="flag"></param>
173         private void CheckedStated(TreeNodeCollection nodes,bool flag) {
174             
175             if (nodes != null)
176             {
177                 foreach (TreeNode node in nodes)
178                 {
179                     node.Checked = flag;
180                     CheckedStated(node.Nodes, flag);
181                 }
182             }
183         }
184     }
185 }
View Code


備注:

性能計數器類別獲取出現異常的解決方案:

在CMD命令窗口中,執行 LODCTR /R 重置性能計數器。如下圖所示:

如果依然不行,嘗試以管理員身份運行【勾上】,如下圖所示:

 --------------------------------------------------------------------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM