本例使用C# PerformanceCounter 对象完成对计算机性能的监视。
关于PerformanceCounter对象可自行MSDN
程序中还通过C#自带的Chart控件实现对数据的实时统计。如下图所示
图表会根据时间来自行滚动,保留的最大长度为180秒。
其中图表的关键代码如下:
[C#] 纯文本查看 复制代码 public void AddNewPoint(DateTime timeStamp, System.Windows.Forms.DataVisualization.Charting.Series ptSeries, double value)
{
ptSeries.Points.AddXY(timeStamp.ToOADate(), value);
//移出过时的数据
double removeBefore = timeStamp.AddSeconds((double)(180) * (-1)).ToOADate();
while (ptSeries.Points[0].XValue < removeBefore)
{
ptSeries.Points.RemoveAt(0);
}
//重新确定X轴的范围
chart1.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
chart1.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddSeconds(200).ToOADate();
//重新确定Y轴的范围
if (value>= chart1.ChartAreas[0].AxisY.Maximum)
{
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = Convert.ToInt64((value+value*0.1)==0?100: value + value * 0.1);
}
chart1.Invalidate();
}
/// <summary>
/// Method which is invoked from the thread to add series points
/// </summary>
public void AddData(double value)
{
DateTime timeStamp = DateTime.Now;
//遍历图例
foreach (Series ptSeries in chart1.Series)
{
AddNewPoint(timeStamp, ptSeries,value);
}
}
private void ChartInit(string seriesname,string initvalue)
{
//初始化图例
minValue = DateTime.Now;
maxValue = minValue.AddSeconds(60);
chart1.ChartAreas[0].AxisX.Minimum = minValue.ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = maxValue.ToOADate();
chart1.Series.Clear();
Series newSeries = new Series(seriesname);
newSeries.ChartType = SeriesChartType.Line;
newSeries.BorderWidth = 1;
newSeries.Color = Color.FromArgb(224, 64, 10);
newSeries.ShadowOffset = 1;
newSeries.XValueType = ChartValueType.DateTime;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 100;
chart1.Series.Add(newSeries);
}
大概就是这样了。源码在下面下载咯~
|