在 windows 服务中配置性能监视器,核心做法是向操作系统注册自定义的性能计数器(performance counters),让服务启动时自动暴露数据供 perfmon 或 powershell 读取。你需要使用 performancecountercategory 类创建类别、实例和计数器,并在服务生命周期中更新这些计数器的值。这样配置后,打开“性能监视器”即可看到该服务的实时指标。

如何注册自定义性能计数器类别
要注册自定义性能计数器类别,需调用 PerformanceCounterCategory.Create 方法,并指定类别名称、类型及包含的计数器定义。建议在服务安装阶段(如通过 ServiceBase.Install)执行此操作,确保权限正确且避免重复注册。若类别已存在,直接调用会抛出异常,因此应先检查是否存在再决定创建或跳过。

using System;
using System.Diagnostics;
using System.ServiceProcess;
public class MyService : ServiceBase
{
private PerformanceCounter _counter;
private const string CategoryName = "MyCustomService";
private const string CounterName = "RequestsProcessed";
protected override void OnStart(string[] args)
{
if (!PerformanceCounterCategory.Exists(CategoryName))
{
var counters = new CounterCreationDataCollection
{
new CounterCreationData
{
CounterName = CounterName,
CounterType = PerformanceCounterType.NumberOfItems32
}
};
PerformanceCounterCategory.Create(
CategoryName,
"Custom performance data for MyService",
PerformanceCounterType.SingleInstance,
counters);
}
_counter = new PerformanceCounter(
CategoryName,
CounterName,
false); // Not an instance-specific counter
_counter.Increment(); // Initial value
}
protected override void OnStop()
{
_counter?.Dispose();
}
}
上述代码在服务启动时检查类别是否存在,若不存在则创建名为 MyCustomService 的单实例类别,内含一个类型为 NumberOfItems32 的计数器 RequestsProcessed。启动后首次调用 Inrement() 将初始值设为 1。停止服务时释放资源。运行此服务后,可在性能监视器中添加 MyCustomService\RequestsProcessed 查看数值变化。
通过 Clawdos API 实现 Windows 自动化:屏幕捕获、鼠标/键盘输入、窗口管理、文件系统操作和 Shell 命令执行。独立版...
如何在运行时动态更新计数器值
在运行时动态更新计数器值,只需获取已创建的 PerformanceCounter 实例并调用其 Increment()、Decrement() 或 SetValue() 方法。不同计数器类型支持的操作不同:例如 NumberOfItems32 支持增量/减量,而 AverageTimer32 需要配合 AverageBase 使用。务必确保线程安全,因为多个线程可能同时调用更新方法。

using System;
using System.Diagnostics;
using System.Threading;
public class CounterUpdater
{
private readonly PerformanceCounter _counter;
private volatile bool _running = true;
public CounterUpdater(string category, string counter)
{
_counter = new PerformanceCounter(category, counter, false);
}
public void StartUpdating()
{
while (_running)
{
try
{
// Simulate processing work
Thread.Sleep(1000);
_counter.Increment();
}
catch (Exception ex)
{
Console.WriteLine($"Update failed: {ex.Message}");
}
}
}
public void StopUpdating()
{
_running = false;
_counter.Dispose();
}
}
该示例展示了一个独立的计数器更新器类,它持有对特定类别和计数器的引用,并在后台循环中每秒递增一次。使用 volatile 标志位控制循环退出,避免强制终止导致资源泄漏。在实际服务中,可将此类集成到 OnStart 中作为独立任务运行。注意:若计数器类型为 RateOfCountsPerSecond32 等基于时间的类型,需额外维护基础计数器以计算速率,否则值将不准确。
当计数器类型为 NumberOfItems32 时,SetValue 是否有效
当计数器类型为 NumberOfItems32 时,调用 SetValue() 是有效的,但行为取决于具体实现:它会直接设置计数器的当前值为传入参数,而非基于原值进行运算。这意味着后续调用 Increment() 将从新设定的值开始累加。这种特性适用于需要重置或同步外部状态的场景,但需谨慎使用以避免数据不一致。


















