Ask the Expert

Extending simple performance counter retrieval to array

I tried to extend simple performance counter retrieval to array. It is OK when I build the code, but I got the following message pointing to perfCounter(loopCount) = New PerformanceCounter(tmpCs(0), tmpCs(1), tmpCs(2), "MYPC") when I debug it.

An unhandled exception of type 'System.NullReferenceException' occurred in ConsoleApplication1.exe.

Additional information: Object reference not set to an instance of an object.

Any idea why this is happening? Thanks in advance. The code is as follows:

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data

Module Module1

    Sub Main()
        Dim perfCounters As String()
        Dim tmpC As String
        Dim tmpCs As String()
        Dim perfCounter As PerformanceCounter()
        Dim loopCount As Integer

        perfCounters = New String() {"Processor\% Processor Time\_Total", _
                                     "Processor\% User Time\_Total"}

        'perfCounter = New PerformanceCounter() {}

        loopCount = 0
        For Each tmpC In perfCounters
            loopCount += 1
            tmpCs = Split(tmpC, "\\")
            perfCounter(loopCount) = New PerformanceCounter(tmpCs(0), tmpCs
(1), tmpCs(2), "MYPC")
        Next tmpC

        For loopCount = 1 To perfCounters.Length

    End Sub

End Module

You failed to initialize the perfCounter array. The NullReference exception is when you try to assign the returned PerformanceCounter class to perfCounter(loopCount).

This was first published in April 2004

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: