让我们的多实例性能计数器在ASP.NET MVC 3中工作时遇到问题。将其创建为单个实例效果良好,在一个简单的控制台应用程序中运行我们的多实例性能计数器代码也很好。但是,当我创建它的多实例并尝试使用ASP.NET来增加它时,它会遇到困难。
我没有例外。我只是在perfmon中看不到任何测量输出。然而,我可以看到这两个例子。
这是控制台应用程序代码,用于创建性能计数器类别:
private const string PERF_COUNTER_CATEGORY_NAME = "MvcPerformance";
private const string PERF_COUNTER_BASE_NAME = "MvcAction_Base";
private const string PERF_COUNTER_NAME = "MvcAction";
static void Main(string[] args)
{
if (PerformanceCounterCategory.Exists(PERF_COUNTER_CATEGORY_NAME))
{
PerformanceCounterCategory.Delete(PERF_COUNTER_CATEGORY_NAME);
}
CounterCreationDataCollection counters = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData avgDuration = new CounterCreationData();
avgDuration.CounterType = PerformanceCounterType.AverageTimer32;
avgDuration.CounterName = PERF_COUNTER_NAME;
counters.Add(avgDuration);
CounterCreationData avgDurationBase = new CounterCreationData();
avgDurationBase.CounterName = PERF_COUNTER_BASE_NAME;
avgDurationBase.CounterType = PerformanceCounterType.AverageBase;
counters.Add(avgDurationBase);
// Create the category.
PerformanceCounterCategory.Create(PERF_COUNTER_CATEGORY_NAME, "Performance counters for MVC!", PerformanceCounterCategoryType.MultiInstance, counters);
}
然后我们在ASP.NET MVC应用程序中的HomeController看起来像这样:
private static readonly Random _Random = new Random(); private const string PERF_COUNTER_CATEGORY_NAME = "MvcPerformance"; private const string PERF_COUNTER_BASE_NAME = "MvcAction_Base"; private const string PERF_COUNTER_NAME = "MvcAction"; private static PerformanceCounter _MvcActionCounter = new PerformanceCounter { CounterName = PERF_COUNTER_NAME, CategoryName = PERF_COUNTER_CATEGORY_NAME, ReadOnly = false, InstanceName = "Home_Index", }; private static PerformanceCounter _MvcActionCounterBase = new PerformanceCounter { CounterName = PERF_COUNTER_BASE_NAME, CategoryName = PERF_COUNTER_CATEGORY_NAME, ReadOnly = false, InstanceName = "Home_Index_Base", }; public ActionResult Index() { Stopwatch s = new Stopwatch(); s.Start(); Thread.Sleep(_Random.Next(1000)); s.Stop(); // Increment the performance counters. _MvcActionCounter.IncrementBy(s.ElapsedMilliseconds); _MvcActionCounterBase.Increment(); return View(new HomeViewModel { ElapsedTime = s.Elapsed }); }
这可能是我很容易忘记的事情。也许与权限或用户管理有关?
我的一位同事刚刚给我邮寄了答案。基本计数器的实例名称必须与平均计数器的实例名相同。
如果你遇到这样的问题,请确保这是你检查的第一件事。。。可以为你节省很多时间。