C# PerformanceCounter-自定义计数器文件视图内存不足

C# PerformanceCounter-自定义计数器文件视图内存不足,c#,.net,exception,performancecounter,C#,.net,Exception,Performancecounter,在对.Net Win32应用程序进行负载测试时,我遇到了一些异常: System.TypeInitializationException: The type initializer for 'MyClass' threw an exception. ---> System.InvalidOperationException: Custom counters file view is out of memory. at System.Diagnostics.SharedPerforma

在对.Net Win32应用程序进行负载测试时,我遇到了一些异常:

System.TypeInitializationException: The type initializer for 'MyClass' threw an exception. ---> System.InvalidOperationException: Custom counters file view is out of memory.
   at System.Diagnostics.SharedPerformanceCounter.CalculateMemory(Int32 oldOffset, Int32 totalSize, Int32& alignmentAdjustment)
   at System.Diagnostics.SharedPerformanceCounter.CreateInstance(CategoryEntry* categoryPointer, Int32 instanceNameHashCode, String instanceName, PerformanceCounterInstanceLifetime lifetime)
   at System.Diagnostics.SharedPerformanceCounter.GetCounter(String counterName, String instanceName, Boolean enableReuse, PerformanceCounterInstanceLifetime lifetime)
   at System.Diagnostics.SharedPerformanceCounter..ctor(String catName, String counterName, String instanceName, PerformanceCounterInstanceLifetime lifetime)
   at System.Diagnostics.PerformanceCounter.InitializeImpl()
   at System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly)
运行此线路时会发生以下情况:

new PerformanceCounter("CategoryName", "CounterName", "InstanceName", false);
我对性能计数器不是很熟悉,通过看到这条消息,我知道它们存储在某个文件中,但这是开发人员清除该文件的责任吗?如果是,怎么做?如果没有,我该怎么办


我有5个此应用程序的实例在同一台计算机上运行。

性能计数器实现IDisposable,因此您可以使用

直接:

 perfCounter.Close();
 perfCounter.Dispose();
间接地:

using(PerformanceCounter perfCounter=new PerformanceCounter())
{
   //Your Code.
}
清理其资源

您还可以使用注册表为性能计数器分配更多内存。请参阅文档中的这篇文章:


与.NET Framework 2.0一起安装的性能计数器类别使用单独的共享内存,每个性能计数器类别都有自己的内存。您可以通过在注册表项HKEY\U LOCAL\U MACHINE\SYSTEM\CurrentControlSet\Services\\Performance中创建名为FileMappingSize的DWORD来指定单独共享内存的大小。FileMappingSize值设置为类别的共享内存大小。默认大小为131072十进制。如果FileMappingSize值不存在,则会使用Machine.config文件中指定的performanceCounters元素的FileMappingSize属性值,从而导致配置文件处理的额外开销。通过在注册表中设置文件映射大小,可以提高应用程序启动的性能。有关文件映射大小的更多信息,请参阅元素。

Ok,但在我的示例中,我在启动时创建性能计数器,并在关闭应用程序时关闭它们,在中间,我有几个调用增加了正好相反的两个选项:每当你用完内存并创建另一个和/或增加分配给你的计数器的内存时,处理PrimeCube,这样你就不会有例外,没有一种方法可以在不经过注册表修改的情况下增加内存吗?我的意思是我们不能确定其他人不会修改这个数字,不是吗?以前有一个函数调用来增加内存分配,但现在已经过时了。这意味着,即使你不输入注册表项,我也可以稍后再输入。基本上,其他人可以随时修改该数字。好吧,不管怎样,我在这里与人核实过,我们不能添加一些注册表值,因为应该可以拖放一些文件。难道没有办法在整个应用程序范围内增加内存吗?这不是您在进行“负载测试”时所期望的吗?计数器由内存映射文件支持,以存储计数器数据。该文件有一个预设限制,默认为32768字节。创建太多的计数器,您的空间不足。你可以通过入侵注册表来改变限制。别这样。