Search code examples
c#windows-servicesperformancecounter

.Net Performance Counters Get Corrupted When I Call Them


This seems like maybe a common problem? I ave written a Windows Service that grabs a bunch of performance counters and reads them and reports them. I am grabbing them like so:

public override IEnumerable<IMetric> GetMetrics()
{
    var metrics = new List<IMetric>();
    try
    {
        using (var performanceCounter = new PerformanceCounter(PerformanceCounterCategoryName,
            PerformanceCounterName, InstanceName))
        {
            performanceCounter.NextValue();

            Thread.Sleep(SampleInterval);

            var nextValue = performanceCounter.NextValue();
            metrics.Add(new Metric(HostId, $"{PerformanceCounterCategoryName}:{PerformanceCounterName}",
                nextValue, MetricType.Gauge));
        }

        Logger.Debug($"{PerformanceCounterName} metric retrieved.");
    }
    catch (InvalidOperationException e)
    {
        Logger.Error(e,$"Monitor {nameof(GetType)} failed. Performance counter {PerformanceCounterCategoryName}:{PerformanceCounterName} does not exist.");
    }
    catch (Exception e)
    {
        Logger.Error(e, e.Message);
    }

    return metrics;
}

I call this on about 30 performance counters every 5 minutes. The problem is, as soon as I start up my service, the counters get corrupt, especially the .Net Memory counters, and I have to remove them:

unlodctr "C:\Windows\INF\.NETFramework\corperfmonsymbols.ini"

Rebuild them:

lodctr /R

Reinstall them:

lodctr "C:\Windows\INF\.NETFramework\corperfmonsymbols.ini"

But as soon as I start up my service they get corrupted again. How do I keep them stable?


Solution

  • It seems like this had to do with 32 vs 64 bit. I tried to set up the application as 64 bit application and apparently I did not have it configured correctly. As soon as I switched back to 32 bit it worked perfectly.