PerformanceCounter array within Constructor

J

jimbo

Here is my problem. I'm creating an Instrumentation class that will use
previously created Performance Categories and Counters in order to time
various processes (ie. query duration etc.). This Instrumentation class
will be used by a variety of "services", so the Categories and Counters
to be used within the object must be set during object construction.

So I created a class variable array of:

private static PerformanceCounter[] arrayCounters = null;

I created an overloaded constructor:

public Instrumentation(string logName, string PerfCategory, string[]
PerfCounters, string CASContext)

The parameters are passed in by the consuming service, with the
PerformanceCounters to be tracked in the form of a string array.

Within the constructor, I process the string array and try to set the
array members of PerformanceCounter array:

long arrayCountersIndex = 0;
foreach (string counter in PerfCounters)
arrayCounters[arrayCountersIndex++] = new
PerformanceCounter(PerfCategory, counter, false);

The solution builds with no errors, but as soon as the previous code
line is executed during testing I get a "System.NullReferenceException:
Object reference not set to an instance of an object." error on the
arrayCounters object.

The constructor will work if I comment out the setting of the array and
hard code the original class variable like this:

private static PerformanceCounter[] arrayCounters = {new
PerformanceCounter("ServiceName", "ServiceLocationDuration", false),
new PerformanceCounter("ServiceName", "OracleConnectionDuration",
false),
new PerformanceCounter("ServiceName", "QueryDuration", false),
new PerformanceCounter("ServiceName", "WebServiceDuration", false)};

Any help I could get with getting that constructor array to work would
be greatly appreciated.

Thanks - jimbo
 
N

Nicholas Paldino [.NET/C# MVP]

Jimbo,

You have to declare the space for the array before you assign it.
Basically, in your constructor, before you look through the PerfCounters
array, you should do this:

// Allocate the array.
arrayCounters = new PerformanceCounter[PerfCounters.Length];

And this will allocate your array. Of course, if PerfCounters is null,
you will get an error, so make that check beforehand. Other than that, the
code should work fine.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top