如何诊断消耗高 CPU 的 dotnet 进程?

How to diagnose dotnet process consuming high CPU?

我在 Kubernetes 中有一个 ASP.NET 核心进程 运行。突然出现问题,CPU 使用率从 8% 跃升至 100% 并稳定在该水平。内存使用没有改变,所以它看起来像一个线程中的无限循环。

我可以使用哪些工具来诊断过程中发生的情况?

我应该怎么做才能在将来诊断此类问题?

.net 核心支持一些命令让我们诊断 CPU 高或内存问题。

首先,安装工具

dotnet tool install --global dotnet-trace
dotnet tool install --global dotnet-counters

然后我们可以使用dotnet-trace ps获取我们要跟踪的进程ID。

然后使用dotnet-counters命令我们可以看到进程使用资源的情况。

dotnet-counters monitor -p 22884 --refresh-interval 1
  • -p: 你要跟踪哪个进程id
  • --refresh-interval: 从命令行刷新监控屏幕的频率window(单位是秒)

if you want to only focus on cpu-usage you can try to add this parameter --counters System.Runtime[cpu-usage]

当我们使用上面的命令时,我们会得到很多运行时信息,可以帮助我们从您的进程中进行诊断。

[System.Runtime]
% Time in GC since last GC (%)                          
Allocation Rate (B / 1 sec)                             
CPU Usage (%)                                           
Exception Count (Count / 1 sec)                         
GC Committed Bytes (MB)                                 
GC Fragmentation (%)                                    
GC Heap Size (MB)                                       
Gen 0 GC Count (Count / 1 sec)                          
Gen 0 Size (B)                                          
Gen 1 GC Count (Count / 1 sec)                          
Gen 1 Size (B)                                        
Gen 2 GC Count (Count / 1 sec)                        
Gen 2 Size (B)                                        
IL Bytes Jitted (B)                                   
LOH Size (B)                                           
Monitor Lock Contention Count (Count / 1 sec)           
Number of Active Timers                                 
Number of Assemblies Loaded                             
Number of Methods Jitted                                
POH (Pinned Object Heap) Size (B)                       
ThreadPool Completed Work Item Count (Count / 1 sec)    
ThreadPool Queue Length                                 
ThreadPool Thread Count                                 
Time spent in JIT (ms / 1 sec)                          
Working Set (MB)                                        

更多细节你可以看Debug high CPU usage in .NET Core & dotnet-counters