I'm writing a UI based application in WPF on VSCode. Im trying to have the hardware performance specs update labels on the UI but i'm met with the error when i try to hand-off the total CPU Usage from PerformanceCounter to BackgroundWorker so it can update the UI accordingly in a separate thread
Here's the code-behind the window I intend on displaying the Hardware stats
Monitor.xaml.cs
public partial class Hostile_Monitor : Window
{
readonly BackgroundWorker bgWorker = new BackgroundWorker();
PerformanceCounter PerfCPUCounter = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
PerformanceCounter PerfCPUFreqCounter = new PerformanceCounter("Processor Information", "Processor Frequency", "_Total");
PerformanceCounter PerfMemCounter = new PerformanceCounter("Memory", "Available MBytes");
public Hostile_Monitor()
{
InitializeComponent();
//Create Backgroundwroker Object
bgWorker = new BackgroundWorker();
//Add DoWork EventHandler
bgWorker.DoWork += BackgroundWorker1_DoWork;
//Progress changed EventHandler
bgWorker.ProgressChanged += BackgroundWorker1_ProgressChanged;
//RunWorkerCompleted EventHandler
//bgWorker.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
//Allow to be cancelled
bgWorker.WorkerSupportsCancellation = true;
//allow to report progress
bgWorker.WorkerReportsProgress = true;
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i > 0; i++)
{
Console.WriteLine(i);
bgWorker.ReportProgress(PerfCPUCounter); // This line is where the error occurs @->(PerfCPUCounter);
System.Threading.Thread.Sleep(500);
if (bgWorker.CancellationPending)
{
Console.WriteLine("Thread is exiting...");
break;
}
}
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.Label1.Content = e.ProgressPercentage;
private void ButtonPower_Click(object sender, RoutedEventArgs e)
{
if (bgWorker.IsBusy)
{
bgWorker.RunWorkerAsync();
ButtonPower.Content = "Stop Monitor";
} else
{
bgWorker.CancelAsync();
ButtonPower.Content = "Start Monitor";
}
This is my first attempt at developing a desktop application so any tips would be greatly appreciated Hopefully i included all necessary code for you guys to get an idea of what's going on
Try this:
bgWorker.ReportProgress((int)Math.Round( PerfCPUCounter.NextValue()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.