C#利用性能计数器监控网络状态

时间:2022-09-11 12:41:19

本例是利用c#中的性能计数器(performancecounter)监控网络的状态。并能够直观的展现出来

涉及到的知识点:

performancecounter,表示 windows nt 性能计数器组件。nextvalue() 即获取计数器样本并为其返回计算所得值。performancecountercategory 表示性能对象,它定义性能计数器的类别。通过这两个即可得到计数器的信息。

chart 图表,vs自带的chart图表,大大简化了对图表的开发。关于chart,此前已有例子说明。

queue 队列表示对象的先进先出集合。关于queue此前已有例子说明。

treeview 显示标记项的分层集合,每个标记项用一个 system.windows.forms.treenode 来表示。即vs自带的树状菜单

timer 实现按用户定义的时间间隔引发事件的计时器。此计时器最宜用于 windows 窗体应用程序中,并且必须在窗口中使用。定时刷新计数器中的值。

效果图如下:

C#利用性能计数器监控网络状态

关于可用的计数器列表【计数器有很多,一级菜单是计数器的类别,二级菜单是计数器instancename,三级菜单是计数器名称】,如下图所示:

C#利用性能计数器监控网络状态

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.windows.forms.datavisualization.charting;
using system.diagnostics;
 
namespace demosharp
{
  public partial class networkmonitor : form
  {
    private performancecounter mcounter;//当前计数器
 
    private queue<double> dataqueue = new queue<double>(100);//初始化队列
 
    public networkmonitor()
    {
      initializecomponent();
      initcountercategory();
      initchart();
    }
 
    /// <summary>
    /// 初始化计数器信息
    /// </summary>
    private void initcountercategory() {
      //获取所有的计数器类别
      var countercategories = performancecountercategory.getcategories().orderby(p=>p.categoryname);
      int i=0;
      foreach (var countercategory in countercategories) {
        //属于线程级别的不显示
        if (countercategory.categoryname == "thread") {
          continue;
        }
        //将信息绑定的treeview上
        this.tvcategory.checkboxes = true;
        this.tvcategory.nodes.add(countercategory.categoryname);
        string[] instancenames = countercategory.getinstancenames();
        int j = 0;
        foreach (var instancename in instancenames) {
          this.tvcategory.nodes[i].nodes.add(instancename);
          var counters = countercategory.getcounters(instancename).select(p=>string.format("{0}",p.countername));
          int k = 0;
          foreach (var counter in counters) {
            this.tvcategory.nodes[i].nodes[j].nodes.add(counter);
            k++;
          }
          j++;
        }
        i++;
      }
      //初始化counter
      performancecountercategory pccategory = new performancecountercategory("network interface");
      string[] inames = pccategory.getinstancenames();
      performancecounter[] pcounters = pccategory.getcounters(inames[0]);
      //给网络监控计数器赋值
      mcounter = pcounters[0];
      mcounter.nextvalue();//初始值
    }
 
     //<summary>
     //初始化图表
     //</summary>
    private void initchart()
    {
      //定义图表区域
      this.chart1.chartareas.clear();
      chartarea chartarea1 = new chartarea("c1");
      this.chart1.chartareas.add(chartarea1);
      //定义存储和显示点的容器
      this.chart1.series.clear();
      series series1 = new series("s1");
      series1.chartarea = "c1";
      this.chart1.series.add(series1);
      //设置图表显示样式
      this.chart1.chartareas[0].axisy.arrowstyle = axisarrowstyle.sharptriangle;
      this.chart1.chartareas[0].axisy.title = "kkbps";//坐标轴的标题
      this.chart1.chartareas[0].axisy.textorientation = textorientation.rotated270;
      this.chart1.chartareas[0].axisy.minimum = 0;
      this.chart1.chartareas[0].axisy.maximum = 50;
      this.chart1.chartareas[0].axisy.interval = 5;
      this.chart1.chartareas[0].axisx.interval = 5;
      this.chart1.chartareas[0].axisx.arrowstyle = axisarrowstyle.sharptriangle;
      this.chart1.chartareas[0].axisx.title = "sec";
      this.chart1.chartareas[0].axisx.textorientation = textorientation.horizontal;
      this.chart1.chartareas[0].axisx.majorgrid.linecolor = system.drawing.color.silver;
      this.chart1.chartareas[0].axisy.majorgrid.linecolor = system.drawing.color.silver;
      //设置标题
      this.chart1.titles.clear();
      this.chart1.titles.add("s01");
      this.chart1.titles[0].text = "xxx网络监控显示";
      this.chart1.titles[0].forecolor = color.royalblue;
      this.chart1.titles[0].font = new system.drawing.font("microsoft sans serif", 12f);
      //设置图表显示样式
      this.chart1.series[0].color = color.lightgreen;
      this.chart1.series[0].charttype = seriescharttype.area;//图表形状
      this.chart1.series[0].points.clear();
    }
 
    /// <summary>
    /// 启动定时器
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnstart_click(object sender, eventargs e)
    {
      this.timer1.start();
      
    }
 
    /// <summary>
    /// 停止定时器
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnstop_click(object sender, eventargs e)
    {
      this.timer1.stop();
    }
 
    /// <summary>
    /// 定时执行函数
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void timer1_tick(object sender, eventargs e)
    {
      updatequeuevalue();
      this.chart1.series[0].points.clear();
      if (dataqueue.max() > this.chart1.chartareas[0].axisy.maximum) {
        this.chart1.chartareas[0].axisy.maximum = math.ceiling(dataqueue.max() / 10) * 10;
        this.chart1.chartareas[0].axisy.interval = this.chart1.chartareas[0].axisy.maximum / 10;
      }
      for (int i = 0; i < dataqueue.count; i++)
      {
        this.chart1.series[0].points.addxy((i + 1), dataqueue.elementat(i));
      }
    }
 
     //更新队列中的值
    private void updatequeuevalue()
    {
 
      if (dataqueue.count > 100)
      {
        dataqueue.dequeue();
      }
      //获取的值就byte/s 所以要除以1024
      dataqueue.enqueue(mcounter.nextvalue() / (1024));
 
    }
 
    /// <summary>
    /// 当选中复选框时发生
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void tvcategory_aftercheck(object sender, treevieweventargs e)
    {
      bool flag = e.node.checked;//取得选中状态,所有子节点的状态保持一致
      checkedstated(e.node.nodes, flag);
    }
 
    /// <summary>
    /// 采用递归方法修改节点的选中状态
    /// </summary>
    /// <param name="nodes"></param>
    /// <param name="flag"></param>
    private void checkedstated(treenodecollection nodes,bool flag) {
      
      if (nodes != null)
      {
        foreach (treenode node in nodes)
        {
          node.checked = flag;
          checkedstated(node.nodes, flag);
        }
      }
    }
  }
}

备注:性能计数器类别获取出现异常的解决方案:

在cmd命令窗口中,执行 lodctr /r 重置性能计数器。如下图所示:

C#利用性能计数器监控网络状态

如果依然不行,尝试以管理员身份运行【勾上】,如下图所示:

C#利用性能计数器监控网络状态

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。