Visual Basic.NET 7.x (2002/03)Visual Basic 9 (2008)Visual Basic 8 (2005)Visual Studio 2005.NET 2.0中级开发Visual StudioWindows.NETVisual Basic
性能监视器轻松上手!
使用 .NET 诊断从任何 Windows 性能监视器中提取数据,从而创建您自己的性能监视器!
引言
这是一种使用 .NET 框架诊断从您的 PC 检索任何性能信息,并创建您自己的监视器的简单方法。 此演示提供了一个示例,说明如何检索本地计算机上的当前 CPU 使用率,并将结果输出到控制台窗口。
背景
我花了一段时间才弄清楚,您可能会发现关于性能监视器的文章或示例并不多。 我找到了许多描述如何创建自定义监视器的文章,但我需要的是提取信息并存储结果。
此代码的一个用途是向管理员发送电子邮件警报,关于处理器利用率、内存利用率等超出指示机器可能出现问题的参数范围的情况。 此外,通过随着时间的推移收集和存储此信息,您可以跟踪 PC 上的趋势。 我将尽快发布一篇配套文章,其中包含用于显示 PC 上所有进程的 CPU 使用率/内存使用率的代码,就像您在任务管理器中看到的那样。
使用代码
启动一个新的控制台项目 (VB.NET) 并使用下面的代码。
Module SimplePerformanceMonitor
'This sets up a global variable thread
Public TH1 As New _
System.Threading.Thread(AddressOf PerformancMonitor)
'Sub Main is the starting point
'of the application and starts the thread.
Sub Main()
TH1.Start()
End Sub
Public Sub PerformancMonitor()
Dim bForever As Boolean = False
Dim iFrequency As Integer = 1000
Dim pCounter As System.Diagnostics.PerformanceCounter
'*******************************************************************
'***These variables can be interchanged depending
' on which performance object to watch. ***
'***Open the windows performance monitor, right click
' and add counter to see a list of options.***
'*******************************************************************
'This is the Perfomance Object.
Dim sCategory As String = "Processor"
'This represents the counter
Dim sCounter As String = "% Processor Time"
'This represents the instance of the counter
Dim sInstance As String = "_Total"
Dim Sample As System.Diagnostics.CounterSample
Try
'Setting up the performance counter.
pCounter = New PerformanceCounter
pCounter.CategoryName = sCategory
pCounter.CounterName = sCounter
pCounter.InstanceName = sInstance
'Sets the baseline
pCounter.NextValue()
Sample = pCounter.NextSample
'This is an endless loop controlled by the thread TH1
Do While bForever = False
'Retrieves the calculated data.
Dim nv As Single = pCounter.NextValue()
'Retrieves the Raw data
Dim Sample2 As CounterSample = pCounter.NextSample()
'Keeps rolling avg
Dim avg As Single = CounterSample.Calculate(Sample, Sample2)
Console.WriteLine("% CPU = " & nv.ToString & " -- " & _
"Avg % CPU = " & avg.ToString & _
" , " & Date.Now.ToString)
Threading.Thread.Sleep(1000)
'Pauses loop for 1 second.
Loop
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
关注点
希望这有帮助,祝您玩得开心!
历史
- 原始发布日期 - 2008-10-09。