CPU Last von mehreren CPUs überwachen Verfasst am: 29.06.2009, 14:25
Beschreibung: Mit dieser Klassen kann man die CPU Last von einer oder mehreren CPUs überwachen.
Wichtig: Da diese Klasse die CPUs in eigenen Threads überwacht, muss drauf geachtet werden das wenn man die Werte an die Form übergeben will, man mit Delegates und Invoke arbeiten muss. Ein Beispiel dazu findet man in meinem Kommentar.
Public Event CPULoadChanged(ByVal e As CPULoadEventArgs) Private WatcherCollection As New Generic.Dictionary(Of UShort, Watcher)
Public Sub AddWatcher(ByVal CPU As UShort, Optional ByVal Interval As UInteger = 1000) If WatcherCollection.ContainsKey(CPU) = False Then Dim W As New Watcher(CPU, Interval) AddHandler W.Changed, AddressOf OnCPULoadChanged WatcherCollection.Add(CPU, W) W.Start() End If End Sub
Public Sub RemoveWatcher(ByVal CPU As UShort) If WatcherCollection.ContainsKey(CPU) = True Then WatcherCollection(CPU).Abort() WatcherCollection.Remove(CPU) End If End Sub
Private Sub OnCPULoadChanged(ByVal e As CPULoadEventArgs) RaiseEvent CPULoadChanged(e) End Sub
Private Class Watcher Private mCPU As UShort = 0 Private mInterval As UInteger Private mAbort As Boolean = False Private PerfCounter As PerformanceCounter Public Event Changed(ByVal e As CPULoadEventArgs)
Sub New(ByVal CPU As UShort, ByVal Interval As UInteger) mCPU = CPU mInterval = Interval End Sub
Public Sub Start() PerfCounter = New PerformanceCounter("Processor", "% Processor Time", mCPU.ToString) Dim T As New Threading.Thread(AddressOf Watch) T.Start() End Sub
Public Sub Abort() mAbort = True End Sub
Private Sub Watch() Do If mAbort = True Then mAbort = False Exit Do End If
RaiseEvent Changed(New CPULoadEventArgs(mCPU, PerfCounter.NextValue)) Threading.Thread.Sleep(mInterval) Loop End Sub End Class
Public Class CPULoadEventArgs Private mCPU As UShort Private mCPULoad As Single
Public ReadOnly Property CPU() As UShort Get Return mCPU End Get End Property
Public ReadOnly Property CPULoad() As Single Get Return mCPULoad End Get End Property
Sub New(ByVal CurrCPU As UShort, ByVal CurrCPULoad As Single) mCPU = CurrCPU mCPULoad = CurrCPULoad End Sub End Class End Class [/code]