You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio中自定义.NET Counters不显示问题咨询

.NET 自定义计数器不显示问题排查与疑问解答

一、计数器不显示的常见排查点

  • VS诊断工具面板:调试时确认已选中目标进程,在Counters面板的「Select counters」中手动勾选HatCo.Store这个Meter,自定义指标默认不会自动展示。
  • dotnet-counters 命令正确性:使用指定进程ID和监控范围的命令,示例:
    dotnet-counters monitor --process-id <你的进程PID> HatCo.Store System.Runtime
    
    注意:仅.NET 5及以上版本支持System.Diagnostics.Metrics体系的Counter,.NET Framework需改用旧版PerformanceCounter。
  • ASP.NET应用配置:确认项目未通过配置禁用指标收集,若使用OpenTelemetry等工具,需确保已订阅目标Meter。

二、你的疑问解答

1. 计数器监控与进程的连接方式

.NET诊断工具(VS诊断工具、dotnet-counters等)采用**诊断管道(Diagnostic Pipe)**实现进程间通信:

  • Windows系统基于命名管道,Linux/macOS基于Unix域套接字。
  • 工具通过目标进程的PID自动定位并建立管道连接,无需手动配置端口或套接字地址,所有诊断数据均通过该管道传输。

2. 能否在程序内部查看自定义计数器

可以,提供两种实用方式:

方式一:使用MetricListener监听指标更新

通过内置类订阅自定义Meter的指标,实时获取Counter的更新数据:

using System.Diagnostics.Metrics;

var metricListener = new MetricListener();
metricListener.InstrumentPublished += (instrument, listenerInstance) =>
{
    // 仅监听目标Meter和Counter
    if (instrument.Meter.Name == "HatCo.Store" && instrument.Name == "hatco.store.hats_sold")
    {
        listenerInstance.EnableMeasurementEvents(instrument);
    }
};

metricListener.MeasurementRecorded += (instrument, measurement, tags) =>
{
    Console.WriteLine($"[{DateTime.Now}] 帽子售出计数器值: {measurement}");
};

方式二:同步维护计数器内部值

由于Counter<T>未直接暴露当前累加值,可在递增Counter时同步更新自定义变量:

static Meter s_meter = new Meter("HatCo.Store");
static Counter<int> s_hatsSold = s_meter.CreateCounter<int>("hatco.store.hats_sold");
static int s_hatsSoldInternal = 0; // 同步维护的内部值

// 递增时同步更新
s_hatsSold.Add(1);
Interlocked.Increment(ref s_hatsSoldInternal);

// 内部查看时直接读取
Console.WriteLine($"当前已售出帽子数量: {s_hatsSoldInternal}");

内容的提问来源于stack exchange,提问作者pjc50

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:06:05