C# 性能计数器:未识别的不良行为

C# 性能计数器:未识别的不良行为,c#,performancecounter,C#,Performancecounter,我有一个计数器检查应用程序,它从.Net监视性能计数器[PC] 我正在为PC使用包装器类,以允许同步访问等。 计数器包装器有一个Init方法,其中执行以下代码: PerformanceCounterCategory pcc = new PerformanceCounterCategory(this.categoryName, this.machineName); if(pcc.CounterExists(this.counterName)) { if(this.pc != null)

我有一个计数器检查应用程序,它从.Net监视性能计数器[PC]

我正在为PC使用包装器类,以允许同步访问等。 计数器包装器有一个Init方法,其中执行以下代码:

PerformanceCounterCategory pcc = new PerformanceCounterCategory(this.categoryName, this.machineName);
if(pcc.CounterExists(this.counterName))
{
    if(this.pc != null)    //Could exist from earlier use.
    {
        try
        {
            this.pc.Close();
            this.pc.Dispose();
        }
        catch(Exception ex)
        {
            ...log
        }
    }

    this.pc = new PerformanceCounter(this.categoryName, this.counterName, this.instanceName, this.machineName);
    float value = pc.NextValue();        //Initial read//////-----MARK-----.
}
这段代码最初运行得很好

在一台被监视的计算机脱机后(这在更新方法中注册),将 上面的代码不再工作,要测试该计数器的远程可用性,请使用上面的代码 再次调用“Init”方法。有时这样做有效,有时失败。如果失败,我会看到:

无效手术;消息:无法访问已关闭的注册表项。 对象名称:“HKEY_性能_数据”,来源:mscorlib

这位于上面代码中的标记位置

我预计代码在这里会失败:

PerformanceCounterCategory pcc = new PerformanceCounterCategory(this.categoryName, this.machineName);
if(pcc.CounterExists(this.counterName))
或在此:

this.pc = new PerformanceCounter(this.categoryName, this.counterName, this.instanceName, this.machineName);
但不在“value=this.pc.NetxtValue”[标记的pos]处的“Init”中

框架中似乎有一些奇怪的东西[这不是第一次,我在PerformanceCounters上看到了一些奇怪的东西]

任何帮助都会很好

非常感谢,谢谢 致以最良好的祝愿


++mabra

您关闭并处理PC成员,但您没有将其设置为null,这是您下次调用时的测试内容,因此您可能正在对已关闭的实例调用close。

不可能,它会在其上方的一行上新建。据我所知,是pcc,但不是PC。