性能计数器抛出SecurityException

时间:2012-01-24 05:15:56

标签: performancecounter securityexception

这是代码:

    private static void CreateCounter()
    {
        if (PerformanceCounterCategory.Exists("DemoCategory"))
            PerformanceCounterCategory.Delete("DemoCategory");

        CounterCreationDataCollection ccdArray = new CounterCreationDataCollection();

        CounterCreationData ccd = new CounterCreationData();
        ccd.CounterName = "RequestsPerSecond";
        ccd.CounterType = PerformanceCounterType.NumberOfItems32;
        ccd.CounterHelp = "Requests per second";
        ccdArray.Add(ccd);

        PerformanceCounterCategory.Create("DemoCategory", "Demo category",
            PerformanceCounterCategoryType.SingleInstance, ccdArray);

        Console.WriteLine("Press any key, to start use the counter");
    }

显然:

PerformanceCounterCategory.Create("DemoCategory", "Demo category", 
     PerformanceCounterCategoryType.SingleInstance, ccdArray);

是抛出异常的行。

我已阅读PerformanceCounterPermission,我该怎么做?

1 个答案:

答案 0 :(得分:6)

您的应用程序的进程没有适当的权限级别。这就是安全例外告诉你的。

简单的解决方法是在应用程序启动时请求该权限。您可以通过修改应用程序的清单来执行此操作,以便requestedExecutionLevel设置为requireAdministrator

添加到应用程序清单中的完整部分将如下所示:

<!-- Identify the application security requirements. -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
  <security>
    <requestedPrivileges>
      <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    </requestedPrivileges>
  </security>
</trustInfo>

如果您的应用程序不否则需要管理权限,则可能有更好的选择,因为您应始终以绝对必要或必需的最低权限级别运行。您可以使用Google调查这些替代方案;它将涉及分离请求UAC提升的单独的进程,并在用户明确请求时运行性能计数器。