Der nachfolgende Programmcode demonstriert, wie mit C# die Prozessorauslastung ermittelt und in einer Konsolenanwendung ausgegeben werden kann (funktioniert natürlich auch in einem Windows-Programm). Benötigt werden u.a. die Namespaces System.Diagnostics für die Klasse PerformanceCounter und System.Threading für die Thread-Klasse.
class CpuPerformance
{
static void Main(string[] args)
{
PerformanceCounter processorPerformance =
new PerformanceCounter(„Processor“, „% Processor Time“, „_Total“);
Console.Clear();
Console.Write(„CPU-Auslastung in %:“);
int i = 0;
while (i < 50)
{
Console.SetCursorPosition(22, 0);
Console.Write(„{0,10:0.000}“,processorPerformance.NextValue());
i++;
Thread.Sleep(1000);
}
}
}
Da man heute nicht mehr jedermann mit einer Konsolenanwendung zufrieden stellen kann, folgt auch noch ein Beispiel für ein Windows Forms Programm. Hierbei wird eine Progressbar zur Darstellung der CPU-Auslastung verwendet.
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.Diagnostics;
using System.Threading;
namespace WinPerformanceInfo
{
public partial class Form1 : Form
{
PerformanceCounter processorPerformance;
bool isRunning;
public Form1()
{
InitializeComponent();
InitializeBackgroundWorker();
processorPerformance =
new PerformanceCounter(„Processor“,
„% Processor Time“, „_Total“);
isRunning = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnStop.Enabled = true;
isRunning = true;
bgwCpu.RunWorkerAsync();
}
private void InitializeBackgroundWorker()
{
bgwCpu.DoWork += new DoWorkEventHandler
(bgwCpu_DoWork);
bgwCpu.ProgressChanged += new ProgressChangedEventHandler
(bgwCpu_ProgressChanged);
bgwCpu.WorkerReportsProgress = true;
bgwCpu.WorkerSupportsCancellation = true;
}
private void bgwCpu_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbCpu.Value = e.ProgressPercentage;
}
private void bgwCpu_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
consumingMethod(worker, e);
}
void consumingMethod(BackgroundWorker worker, DoWorkEventArgs e)
{
if (worker.CancellationPending == true)
return;
while (isRunning)
{
worker.ReportProgress((int)processorPerformance.NextValue());
Thread.Sleep(1000);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
bgwCpu.CancelAsync();
btnStop.Enabled = false;
btnStart.Enabled = true;
isRunning = false;
}
}
}