Performance problems in production .NET applications are not always easy to identify. An application may respond slowly, consume more memory than expected, or experience increasing CPU usage without producing an obvious error.
In many situations, developers start investigating by checking application logs or restarting the affected service. However, logs do not always explain what is happening inside the .NET runtime.
This is where dotnet-counters becomes useful.
dotnet-counters is a command-line diagnostic tool that monitors performance counters and runtime metrics from a running .NET application. It helps developers investigate CPU usage, memory allocation, garbage collection, Thread Pool activity, exceptions, and other runtime behaviors without changing application code.
For example, if an ASP.NET Core API suddenly becomes slow, dotnet-counters can help determine whether the application is experiencing high CPU usage, excessive garbage collection, Thread Pool starvation, or increasing memory consumption.
This article explains how to use dotnet-counters effectively, which metrics matter, how to interpret their values, and how to use the collected information to investigate production performance problems.
Understanding dotnet-counters
dotnet-counters is part of the .NET diagnostics tooling ecosystem. It collects performance information published by the .NET runtime and application libraries through EventCounters and the newer System.Diagnostics.Metrics API.
It is particularly useful for first-level performance investigations.
You can use it to:
- Monitor CPU consumption.
- Observe managed heap size and memory allocation.
- Track garbage collection activity.
- Investigate Thread Pool behavior.
- Identify increasing exception rates.
- Monitor application-specific metrics.
- Collect runtime metrics for later analysis.
Unlike a debugger, dotnet-counters does not require you to attach breakpoints or modify application source code.
It connects to a running .NET process through the runtime diagnostic infrastructure and periodically displays selected metrics.
The tool supports Windows, Linux, and macOS, although process permissions, diagnostic socket configuration, and runtime compatibility can affect connectivity.
Installing dotnet-counters
You can install dotnet-counters as a global .NET tool.
Run the following command:
dotnet tool install --global dotnet-counters
If you already have an installation, update it using:
dotnet tool update --global dotnet-counters
Starting with .NET SDK 10.0.100, you can also use dnx to execute the tool without permanently installing it:
dnx dotnet-counters monitor --process-id 12345
For regular development and production troubleshooting, a global installation is convenient.
After installation, verify the tool:
dotnet-counters --version
If the command is not recognized, check whether the .NET global tools directory is included in your system PATH.
Finding the Running .NET Process
Before monitoring an application, identify its process ID.
Use:
dotnet-counters ps
The command displays running .NET processes that can be discovered by the diagnostic tooling.
For example, an application might appear as:
12345 dotnet /app/MyApi.dll
23456 dotnet /app/BackgroundWorker.dll
34567 dotnet /app/NotificationService.dll
If multiple .NET applications are running on the same server, selecting the correct process is important.
For example, an ASP.NET Core API and a background worker may both consume CPU and memory. Monitoring the wrong process can lead to incorrect conclusions.
You can also identify process IDs using operating system tools such as Task Manager, Process Explorer, or the Linux ps command.
Monitoring Runtime Metrics
Once you have the process ID, start monitoring the application.
dotnet-counters monitor --process-id 12345
By default, the tool monitors the System.Runtime provider.
You can also specify the provider explicitly:
dotnet-counters monitor \
--process-id 12345 \
--counters System.Runtime
The terminal displays periodically refreshed metrics.
Press P to pause monitoring, R to resume, and Q to quit.
For a production investigation, it is often useful to change the refresh interval:
dotnet-counters monitor \
--process-id 12345 \
--refresh-interval 5 \
--counters System.Runtime
This refreshes the displayed values every five seconds.
A shorter interval helps observe rapid changes, while a longer interval makes broader trends easier to follow.
Avoid selecting an extremely short interval without a specific reason. The monitoring process itself has some overhead, and rapidly changing values can make interpretation more difficult.
Important Runtime Metrics to Monitor
The System.Runtime provider exposes several metrics that help identify common performance problems.
The exact names and presentation depend on the .NET runtime version and whether the tool is displaying newer Meter-based metrics or older EventCounters.
The following table describes important metrics and their practical uses.
| Metric | What it measures | What to investigate |
| CPU usage | CPU consumption by the application | Expensive methods and CPU saturation |
| Working set | Physical memory currently associated with the process | Overall process memory usage |
| GC heap size | Managed heap size after garbage collection | Managed memory growth |
| Allocation rate | Rate of managed memory allocation | Excessive object creation |
| Gen 0 collections | Frequency of short-lived object collections | Allocation pressure |
| Gen 1 collections | Frequency of intermediate-generation collections | Object survival patterns |
| Gen 2 collections | Frequency of full managed heap collections | Long-lived memory and GC pressure |
| Time in GC | Time spent performing garbage collection | Garbage collection overhead |
| Thread Pool queue length | Work items waiting for Thread Pool execution | Possible Thread Pool starvation |
| Thread Pool thread count | Number of Thread Pool threads | Thread Pool behavior |
| Exception count | Rate of thrown exceptions | Repeated exception generation |
| Monitor lock contention | Contention involving monitor locks | Synchronization bottlenecks |
These metrics should be interpreted together. A single metric rarely provides enough information to identify the root cause.
Diagnosing High CPU Usage
Suppose an ASP.NET Core application begins consuming more CPU after a new release.
Start by monitoring the runtime:
dotnet-counters monitor \
--process-id 12345 \
--counters System.Runtime
Observe CPU usage over several monitoring intervals.
If CPU consumption remains high, investigate whether the application is performing expensive calculations, processing large collections, serializing large responses, or executing background operations.
For example, consider an application that repeatedly calculates statistics for every customer.
public List<CustomerSummary> GetSummaries(
List<Customer> customers)
{
var summaries = new List<CustomerSummary>();
foreach (var customer in customers)
{
var totalOrders = customer.Orders.Count;
var totalAmount = customer.Orders
.Sum(order => order.Amount);
summaries.Add(new CustomerSummary
{
CustomerId = customer.Id,
TotalOrders = totalOrders,
TotalAmount = totalAmount
});
}
return summaries;
}
This code may be perfectly reasonable for a small collection. However, if the application processes hundreds of thousands of customers repeatedly, the operation may consume significant CPU time.
dotnet-counters can help confirm the CPU increase, but it cannot identify the exact method responsible.
For deeper investigation, collect a CPU trace using dotnet-trace and analyze the call stacks.
The correct workflow is to use counters to identify the performance symptom and a profiler to locate the expensive code.
Investigating Memory Growth
Memory-related problems are another important reason to use dotnet-counters.
Consider an API that processes large files or generates reports. After several hours, its memory consumption increases significantly.
Monitor the application:
dotnet-counters monitor \
--process-id 12345 \
--counters System.Runtime
Pay attention to:
- Working set.
- GC heap size.
- Allocation rate.
- Generation 0, Generation 1, and Generation 2 collections.
- Large Object Heap size, where available.
- Heap fragmentation, where available.
Understanding the relationship between these metrics is important.
For example, an increasing allocation rate does not automatically indicate a memory leak. It may simply mean that the application creates many short-lived objects.
However, if managed heap size continues increasing after garbage collection, investigate whether objects are being retained unexpectedly.
Working set and managed heap size are also different measurements. Working set includes memory beyond the managed heap, such as native allocations and other process memory.
If the counters suggest a memory problem, collect a heap snapshot using dotnet-gcdump or a memory dump using dotnet-dump.
These tools provide deeper information about object types, object counts, and references that prevent objects from being collected.
Investigating Garbage Collection Pressure
The Garbage Collector automatically reclaims memory from objects that are no longer reachable.
However, applications that allocate large amounts of temporary data can trigger frequent garbage collection.
For example, consider an API that repeatedly creates large collections and temporary strings while processing requests.
public string GenerateReport(
IEnumerable<Order> orders)
{
var report = new StringBuilder();
foreach (var order in orders)
{
report.AppendLine(
$"{order.Id},{order.CustomerName},{order.Amount}");
}
return report.ToString();
}
For a small report, this is straightforward. For very large reports, the StringBuilder buffer and final string can require substantial memory.
Monitor the following metrics:
- Allocation rate.
- Gen 0 collection frequency.
- Gen 1 collection frequency.
- Gen 2 collection frequency.
- Time spent in garbage collection.
- Managed heap size.
If allocation rate is high and garbage collection occurs frequently, investigate repeated temporary object creation.
If Gen 2 collections become frequent and the application spends more time in garbage collection, investigate long-lived objects, large allocations, and memory retention.
Do not assume that every increase in garbage collection frequency is a problem. The correct interpretation depends on workload, allocation rate, and application response times.
Detecting Thread Pool Problems
The .NET Thread Pool executes many application operations, including ASP.NET Core request processing and asynchronous continuations.
When too many worker threads become blocked, queued work may take longer to execute.
This condition is known as Thread Pool starvation.
Monitor these metrics:
dotnet-counters monitor \
--process-id 12345 \
--counters System.Runtime
Pay attention to Thread Pool queue length, thread count, and completed work item count.
For example, if the queue length increases continuously while request latency increases, the application may not have enough available workers to process queued work promptly.
Investigate application code for blocking patterns such as:
var result = GetDataAsync().Result;
Or:
GetDataAsync().Wait();
Replace these patterns with asynchronous execution:
var result = await GetDataAsync();
Remember that dotnet-counters helps identify the symptom, not the exact blocking method. Use dotnet-stack to inspect thread stacks and dotnet-trace when deeper analysis is required.
Monitor Exceptions and Lock Contention
Repeated exceptions can also affect application performance.
Consider an application that continuously calls an external service and throws an exception whenever the service is unavailable.
public async Task<Customer?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
try
{
return await _httpClient.GetFromJsonAsync<Customer>(
$"/customers/{customerId}",
cancellationToken);
}
catch (HttpRequestException)
{
return null;
}
}
This example handles an HTTP exception, but if the external service remains unavailable, the application may generate many exceptions.
Monitor the exception rate and correlate it with application logs and dependency failures.
Also monitor lock contention.
When multiple threads frequently compete for the same lock, they may spend time waiting instead of performing useful work.
A high lock contention count should lead you to inspect shared collections, synchronization mechanisms, and critical sections.
For asynchronous coordination, consider SemaphoreSlim.WaitAsync rather than blocking a Thread Pool thread with a synchronous wait.
Monitoring Application-Specific Metrics
Built-in runtime metrics explain what is happening inside the .NET runtime. However, they may not explain what is happening in your business operations.
For example, a payment application may need to monitor:
- Number of payment requests.
- Successful payment operations.
- Failed payment operations.
- Average payment processing duration.
- Pending payment operations.
.NET provides System.Diagnostics.Metrics for publishing application-specific metrics.
Consider the following example:
using System.Diagnostics.Metrics;
public class PaymentMetrics
{
private static readonly Meter Meter =
new("PaymentService.Metrics");
private static readonly Counter<long> PaymentCounter =
Meter.CreateCounter<long>("payment.requests");
private static readonly Histogram<double> PaymentDuration =
Meter.CreateHistogram<double>(
"payment.duration",
unit: "ms");
public void RecordPayment()
{
PaymentCounter.Add(1);
}
public void RecordDuration(double duration)
{
PaymentDuration.Record(duration);
}
}
The application publishes a counter for payment requests and a histogram for payment processing duration.
You can monitor the custom meter using:
dotnet-counters monitor \
--process-id 12345 \
--counters PaymentService.Metrics
The meter name is case-sensitive.
This approach makes it possible to correlate runtime performance with actual application activity.
For example, if CPU usage increases at the same time as payment processing volume, the additional CPU consumption may be related to increased workload.
Custom metrics should use appropriate dimensions and avoid high-cardinality values such as customer IDs, email addresses, or individual request identifiers.
Collect Metrics for Later Analysis
Sometimes the performance problem occurs at night, during a scheduled task, or under a workload that cannot be reproduced immediately.
Instead of continuously watching the terminal, use the collect command to save metrics for later analysis.
For example:
dotnet-counters collect \
--process-id 12345 \
--refresh-interval 5 \
--format csv \
--output runtime-metrics.csv
This collects metrics every five seconds and saves them in CSV format.
You can also export JSON:
dotnet-counters collect \
--process-id 12345 \
--refresh-interval 5 \
--format json \
--output runtime-metrics.json
The collected data can be examined later using spreadsheet software, scripts, or other analysis tools.
This is particularly useful when comparing application behavior before and after a deployment.
You can also launch an application through dotnet-counters to collect metrics from startup:
dotnet-counters collect \
--format json \
--counters System.Runtime,Microsoft.AspNetCore.Hosting \
-- dotnet MyApi.dll
This approach is useful for startup-related problems that may disappear after the application has been running for some time.
Using dotnet-counters in Containerized Applications
Many production .NET applications run inside Docker containers or Kubernetes pods.
You can use dotnet-counters inside the container or from a diagnostic environment that can access the target process.
For example, when a container is running, execute a shell inside it:
docker exec -it my-api-container sh
Then locate the .NET process:
dotnet-counters ps
Start monitoring the target process:
dotnet-counters monitor --process-id 1
The process ID may differ depending on how the application is started inside the container.
For Kubernetes, you can use kubectl exec to access the container:
kubectl exec -it my-api-pod -- sh
The diagnostic tool must be available in the container or accessible through an appropriate diagnostic setup.
Also check the container's CPU and memory limits. A process may appear healthy from the host's perspective but still experience resource pressure because the container has a restricted CPU quota or memory limit.
For production environments, consider a controlled diagnostic image or a dedicated diagnostic sidecar rather than permanently adding unnecessary tools to the application image.
Common Mistakes When Using dotnet-counters
Several mistakes can lead to incorrect conclusions during performance investigations.
- Monitoring the wrong process when multiple .NET applications are running.
- Looking at one counter instead of correlating related metrics.
- Treating high allocation rate as proof of a memory leak.
- Assuming working set and managed heap size represent the same memory.
- Interpreting high Thread Pool thread count as automatic evidence of starvation.
- Ignoring application-specific metrics.
- Using very short refresh intervals without a clear diagnostic purpose.
- Collecting metrics without reproducing the workload that causes the problem.
- Running the tool under a different user account without the required diagnostic permissions.
- Ignoring runtime and tool version differences when comparing metric names.
On Linux and macOS, the target process and diagnostic tool may also need to share the same TMPDIR environment variable. The tool generally needs to run as the same user as the target process or with sufficient privileges.
For applications running in restricted containers, verify that the runtime diagnostic port is accessible before starting an investigation.
dotnet-counters vs Other .NET Diagnostic Tools
dotnet-counters is designed for first-level monitoring. Other tools provide deeper information when counters identify a possible problem.
| Tool | Primary purpose | When to use it |
| dotnet-counters | Monitor runtime metrics | First-level performance investigation |
| dotnet-trace | Collect runtime events and performance traces | Finding expensive methods and runtime behavior |
| dotnet-stack | Capture managed thread stacks | Investigating blocked threads |
| dotnet-gcdump | Capture managed heap information | Identifying object types and memory retention |
| dotnet-dump | Collect and analyze process dumps | Investigating deeper memory and process problems |
These tools complement each other.
For example, if dotnet-counters indicates increasing managed heap size, use dotnet-gcdump to investigate object distribution.
If the Thread Pool queue length increases, use dotnet-stack to inspect blocked threads.
If CPU usage remains high, collect a dotnet-trace profile to identify expensive methods.
Best Practices for Production Monitoring
- Monitor CPU, memory, allocation rate, and garbage collection together.
- Establish normal metric ranges under typical application workloads.
- Compare metrics before and after deployments.
- Use custom application metrics to understand business operations.
- Collect CSV or JSON data for problems that occur intermittently.
- Correlate runtime metrics with application logs and distributed traces.
- Verify container CPU and memory limits.
- Restrict access to diagnostic endpoints and collected files.
- Avoid collecting expensive diagnostic data continuously without a clear requirement.
- Use deeper profiling tools after identifying suspicious metrics.
For long-term monitoring, integrate application metrics with an observability platform such as OpenTelemetry-compatible monitoring infrastructure. dotnet-counters is excellent for ad-hoc diagnosis, but it is not a replacement for continuous production monitoring, alerting, and historical metric storage.
Summary
dotnet-counters is a practical diagnostic tool for investigating runtime performance problems in production .NET applications. It provides visibility into CPU usage, memory allocation, garbage collection, Thread Pool activity, exceptions, and application-specific metrics.
Start by identifying the correct process using dotnet-counters ps. Use the monitor command to observe runtime behavior and the collect command to save metrics for later analysis.
When a counter indicates a problem, use the appropriate diagnostic tool to investigate further. For example, use dotnet-trace for CPU profiling, dotnet-stack for blocked threads, dotnet-gcdump for heap analysis, and dotnet-dump for deeper memory investigations.
The most important practice is to interpret metrics together rather than treating individual values as proof of a problem. By combining runtime counters with application-specific metrics and realistic workload testing, developers can identify performance issues earlier and make more reliable production fixes.
Join the conversation! Your thoughts help the community grow.