0

This code used to work, now it throws exception and refuses to work. The code didn't change. I suspect the cause is when I partitioned my disk to add a second partition. The intended purpose is to monitor the %idle time of the physical drive that it's own path is on.

    Try
        Dim drive As String = BunzipInputStream.BinDirectory.Substring(0, 2)
        Dim instname As String = Nothing
        If drive.EndsWith(":"c, StringComparison.Ordinal) Then
            Dim dix = New System.Diagnostics.PerformanceCounterCategory
            dix.CategoryName = "PhysicalDisk"
            For Each px In dix.GetInstanceNames()
                If px.EndsWith(drive, StringComparison.OrdinalIgnoreCase) Then
                    instname = px
                End If
            Next
            diskcounter = New System.Diagnostics.PerformanceCounter()
            diskcounter.CategoryName = "PhysicalDisk"
            diskcounter.CounterName = "% Idle Time"
            diskcounter.InstanceName = instname
            diskcounter.NextValue()
        End If
    Catch ex As Exception
        'ENDS UP HERE AND ABORTS THE MONITOR
        If Not diskcounter Is Nothing Then
            diskcounter.Dispose()
            diskcounter = Nothing
        End If
    End Try

(this is the setup code. There's a timer that calls diskcounter.NextValue() if it is Not Nothing for display).

System.InvalidOperationException occurred
  Message=Counter is not single instance, an instance name needs to be specified.
  Source=System
  StackTrace:
       at System.Diagnostics.PerformanceCounter.NextSample()
       at System.Diagnostics.PerformanceCounter.NextValue()
       at Redacted.PerformanceMon.OnHandleCreated(EventArgs e) in C:\development\redacted\redacted\Forms\PerformanceMon.vb:line XX
  InnerException: 
Joshua
  • 40,822
  • 8
  • 72
  • 132

1 Answers1

1

As Hans Passant said in the comments, your variable instname probably isn't set the way you intend it to.

Aymeric Gaurat-Apelli
  • 1,804
  • 1
  • 13
  • 14