自定义计数器文件视图的内存不足

Him*_*shu 3 c# wcf performancecounter azure

我有一个具有一个Web角色的Azure云项目。部署后,Web角色端点几乎立即返回HTTP 400-错误请求。当我检查跟踪消息日志时,看到以下异常-

Type : System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Custom counters file view is out of memory.
Source : System
Help link : 
Data : System.Collections.ListDictionaryInternal
TargetSite : Int32 CalculateMemory(Int32, Int32, Int32 ByRef)
HResult : -2146233079
Stack Trace :    at System.Diagnostics.SharedPerformanceCounter.CalculateMemory(Int32 oldOffset, Int32 totalSize, Int32& alignmentAdjustment)
   at System.Diagnostics.SharedPerformanceCounter.CreateCategory(CategoryEntry* lastCategoryPointer, 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)
Run Code Online (Sandbox Code Playgroud)

似乎是由于.NET达到允许分配给性能计数器的内存量的上限而引起的。

因此,我尝试通过Web.config中的以下条目来增加内存分配-

<configuration> 
<system.diagnostics> 
<performanceCounters filemappingsize="33554432" /> 
</system.diagnostics> 
</configuration> 
Run Code Online (Sandbox Code Playgroud)

但是即使这样,我仍然会遇到问题。有人可以为我提供一些解决问题的建议吗?

谢谢!

小智 5

您是否在使用自己的性能计数器?我们在其中一个应用程序中创建了性能计数器,但未正确处理它们,因此有一个相同的例外。

请注意,调用PerformanceCounter.Dispose()还不够-它只是继承而已Component.Dispose(),没有添加任何其他功能。

因此,PerformanceCounter.RemoveInstance()在处置多实例PerformanceCounter的实例时,请始终调用,否则PerformanceCounter实例将不断增长,直到保留的内存(默认为512 KB)已满。

示例模式如下所示(this.performanceCounters是具有使用的性能计数器的字典):

public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (this.performanceCounters != null)
        {
            foreach (PerformanceCounter counter in this.performanceCounters.Values)
            {
                counter.RemoveInstance();
                counter.Dispose();
            }

            this.performanceCounters = null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)