1. 程式人生 > 其它 >.net記憶體洩漏

.net記憶體洩漏

使用以下兩個工具進行分析
dotnet-dounters
dotnet-dump

安裝

dotnet tool install --global dotnet-counters
dotnet tool install --global dotnet-dump

檢視程序資訊並找到程序編號

dotnet-counters ps

監視程序

dotnet-counters monitor -p 14660 --refresh-interval 1 監視id為14660的程序,每隔1秒鐘重新整理一次。

[System.Runtime]
% Time in GC since last GC (%) 0 #GC垃圾回收百分比
Allocation Rate (B / 1 sec) 73,440 #記憶體分配量
CPU Usage (%) 0 #CPU使用率
Exception Count (Count / 1 sec) 0 #異常數量
GC Fragmentation (%) 5.437#GC 堆碎片率
GC Heap Size (MB) 22 #GC堆記憶體分配量(消耗記憶體)
Gen 0 GC Count (Count / 1 sec) 0 #0代垃圾回收次數
Gen 0 Size (B) 1,042,696 #0代垃圾回收大小
Gen 1 GC Count (Count / 1 sec) 0 #1代垃圾回收次數
Gen 1 Size (B) 180,520 #1代垃圾回收大小
Gen 2 GC Count (Count / 1 sec) 0 #2代垃圾回收次數
Gen 2 Size (B) 2,014,768 #2代垃圾回收大小
IL Bytes Jitted (B) 448,237 #JIT編譯的IL總節數
LOH Size (B) 16,875,680 #大物件佔用記憶體(大於85000位元組的物件)
Monitor Lock Contention Count (Count / 1 sec) 0 #鎖競爭次數
Number of Active Timers 3 #活動計數器
Number of Assemblies Loaded 108 #程式集載入數量
Number of Methods Jitted 6,086 #JIT編譯的方法總數
POH (Pinned Object Heap) Size (B) 113,608 #固定物件堆的位元組數
ThreadPool Completed Work Item Count (Count / 1 sec) 2 #執行緒池完成任務數量
ThreadPool Queue Length 0 #執行緒池工作項佇列長度
ThreadPool Thread Count 5 #執行緒池執行緒數量

轉儲記憶體檔案

dotnet-dump collect -p 10232 (程序編號)

分析

dotnet-dump analyze dump_20210825_225811.dmp(轉儲檔名)

進入分析模式後檢視記憶體佔用
dumpheap -stat

分析型別具體物件
dumpheap -mt 00007ffe88612360

gcroot -all 000002c054600480 物件編號

開啟GC高併發回收

專案檔案中新增

<ServerGarbageCollection>false</ServerGarbageCollection>
<!--- ServerGarbageCollection : 伺服器垃圾收集 :不會讓記憶體無限增長 -->
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
<!--- ServerGarbageCollection : 併發垃圾收集 :不會讓記憶體無限增長 -->

參考
C# 效能診斷工具 dotnet-counters 的使用
調查效能計數器 (dotnet-counters)
.net最佳實踐二:使用finalize/dispose模式提升垃圾回收器效能
.NET Best Practice No: 2: Improve garbage collector performance using finalize/dispose pattern
『記憶體洩露』在生產環境中,.Net如何定位系統記憶體洩露具體位置
利用dotnet-dump分析docker容器記憶體洩露
dotnet-dump analyze 記憶體洩漏分析
.net Core 記憶體過高問題解決方案