1
Answer

NullReferenceException on Variable

Cos Marchy

Cos Marchy

14y
8.3k
1

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!!
 

 
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;
namespace
Property_Extractor
{
public partial class Form1 : Form
{

protected PerformanceCounter cpuCounter;
protected PerformanceCounter ramCounter;
protected Thread ResourceMonitorThread;
public Form1()
{
Thread ResourceMonitorThread = new Thread(new ThreadStart(ResourceMonitor));
InitializeComponent();
ResourceMonitorThread.Start();
}
private void ResourceMonitor()
{
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.
*/

private string getCurrentCpuUsage()
{
return cpuCounter.NextValue() + "%";
}
/*
Call this method every time you need to get
the amount of the available RAM in Mb
*/

private string getAvailableRAM()
{
return ramCounter.NextValue() + "Mb";
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

}

 
Any ideas?
Thanks
Answers (1)