Hi guys, I am sure this is a simple one for anyone familiar with multi-threading but this one escapes me... Below is some code I am working on the ultimate aim of which is to create a separate thread to update a toolstatus bar with the current memory and cpu data. When the program is run, I get a NullReferenceException on the return statement of the getAvailableRAM() function. It is saying ramCounter is null although for the life of me I cannot see why because when I set a breakpoint in the ResourceMonitor() function just before the status text is updated, the ramCounter variable is initialised!!
C#
using System;
using System.Collections;
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.IO;
using System.Diagnostics;
using System.Threading;
namespaceProperty_Extractor
{
publicpartialclassForm1 : Form
{
protected PerformanceCounter cpuCounter;
protected PerformanceCounter ramCounter;
protected Thread ResourceMonitorThread;
publicForm1()
{
Thread ResourceMonitorThread = new Thread(new ThreadStart(ResourceMonitor));
InitializeComponent();
ResourceMonitorThread.Start();
}
privatevoidResourceMonitor()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time");
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
while (true)
{
this.toolStripStatusLabel1.Text = "Available Memory: " + getAvailableRAM() + " CPU Usage: " + getCurrentCpuUsage();
Thread.Sleep(1000);
}
}
/*
Call this method every time you need to know
the current cpu usage.
*/privatestringgetCurrentCpuUsage()
{
return cpuCounter.NextValue() + "%";
}
/*
Call this method every time you need to get
the amount of the available RAM in Mb
*/privatestringgetAvailableRAM()
{
return ramCounter.NextValue() + "Mb";
}
privatevoidexitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
Any ideas?
Thanks
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Sam HobbsRank #107 · 20.5K reputationPosted Oct 24, 2010, 12:45 PM EDT
0
There is a rumor going around that controls are not thread-safe and that we should not use a control in any thead except the thread that owns the control. Well, actually it is not a rumor; it is very well documented. Microsoft has always stated that a window should not be accessed by any thread other than it's owner. It works in many situatons, but people are so surprised when Windows does not work the way it is supposed to when it actuallly does not work in ways that Microsoft clearly states it could fail.
Sam HobbsRank #107 · 20.5K reputationPosted Oct 24, 2010, 12:45 PM EDT