1. 程式人生 > 程式設計 >一篇文章教你如何排查.NET記憶體洩漏

一篇文章教你如何排查.NET記憶體洩漏

目錄
  • 前言
  • 檢查託管記憶體使用
  • 生成dump檔案
  • 分析 core dump
  • 總結

前言

記憶體洩漏通常表示:一個應用程式的某些物件在完成它的的生命週期後,由於它被其他物件意外引用,導致後續gc無法對它進行回收,長此以往就會導致程式效能的下降以及潛在的 OutOfMemoryException。

這篇我們通過一個記憶體洩漏工具對 .NET Core 程式進行記憶體洩漏分析,如果程式是跑在windows上,那直接可以使用 Visual Studio 進行診斷。

檢查託管記憶體使用

在開始分析記憶體洩漏之前,你一定要有證據證明真的存在記憶體洩漏,這裡可以用 dotnet-counters 來看下應用程式的各個指標來進行驗證。

將程式跑起來

dotnet run

找出程式的 pid,

dotnet-counters ps

4807 DiagnosticScena /home/user/git/samples/core/diagnostics/DiagnosticScenarios/bin/Debug/netcoreapp3.0/DiagnosticScenarios

使用 monitor 啟動監視器,這裡的 --refresh-interval 表示重新整理間隔

dotnet-counters monitor --refresh-interval 1 -p 4807
Press p to pause,r to resume,q to quit.
    Status: Running

[System.Runtime]
    # of Assemblies Loaded                           118
    % Time in GC (since last GC)                       0
    Allocation Rate (Bytes / sec)                 37,896
    CPU Usage (%)                                      0
    Exceptions / sec                                   0
    GC Heap Size (MB)                                  4
    Gen 0 GC / sec                                     0
    Gen 0 Size (B)                                     0
    Gen 1 GC / sec                                     0
    Gen 1 Size (B)                                     0
    Gen 2 GC / sec                                     0
    Gen 2 Size (B)                                     0
    LOH Size (B)                                       0
    Monitor Lock Contention Count / sec                0
    Number of Active Timers                            1
    ThreadPool Completed Work Items / sec             10
    ThreadPool Queue Length                            0
    ThreadPool Threads Count                           1
    Working Set (MB)                                  83

重點看一下 GC Heap Size (MB) 指標,可以看到程式啟動後當前GC堆記憶體為 4M,開啟連結:https://localhost:5001/api/diagscenario/memleak/20000 後再看看GC堆記憶體,可以看到一下子就到 30M 了,如下所示:

GC Heap Size (MB) 30

通過對比記憶體的使用,這下子可以拍胸脯的說,確認記憶體記憶體洩漏。

生成dump檔案

要想分析程式的記憶體洩漏,首先要有訪問GC堆的許可權,這樣就可以分析heap記憶體以及物件之間的關係,然後就可以大膽猜想為啥記憶體沒有得到釋放?要想生成 .Nhttp://www.cppcns.comET Core 程式的dump檔案,可以藉助 dotnet-dump 工具。

dotnet-dump collect -p 4807
Writing minidump with heap to ./core_20190430_185145
Complete

分析 core dump

接下來可以使用 dotnet-dump analyze 對已生成的dump檔案進行分析。

dotnet-dump analyze core_20190430_185145

這裡的 core_20190430_185145 就是你想要分析的dump名,值得一提的是:如果你遇到了 libdl.so cannot be found 錯誤,建議以安裝一下 libc6-dev package 包。

首先我們通過 sos 命令檢視 託管堆 上的所有物件統計清單。

> dumpheap -stat

Statisticwww.cppcns.coms:
              MT    Count    TotalSize Class Name
...
00007f6c1eeefba8      576        59904 System.Reflection.RuntimeMethodInfo
00007f6c1dc021c8     1749        95696 System.SByte[]
00000000008c9db0     3847       116080      Free
00007f6c1e784a18      175       128640 System.Char[]
00007f6c1dbf5510      217       133504 System.Object[]
00007f6c1dc014c0      467       416464 System.Byte[]
00007f6c21625038        6      4063376 testwebapi.Controllers.Customer[]
00007f6c20a67498   200000      4800000 testwebapi.Controllers.Customer
00007f6c1dc00f90   206770     19494060 System.String
Total 428516 objects

從輸出看,大頭都是些 String 和 Customer 物件,然後可以通過 mt 引數來獲取該方法表下所有的例項物件。

> dumpheap -mt 00007faddaa50f90

         Address               MT     Size
...
00007f6ad09421f8 00007faddaa50f90       94
...
00007f6ad0965b20 00007f6c1dc00f90       80
00007f6ad0965c10 00007f6c1dc00f90       80
00007f6ad0965d00 00007f6c1dc00f90       80
00007f6ad0965df0 00007f6c1dc00f90       80
00007f6ad0965ee0 00007f6c1dc00f90       80

Statistics:
              MT    Count    TotalSize Class Name
00007f6c1dc00f90   206770     19494060 System.String
Total 206770 objects

接下來可以用 !gcroot 檢視某一個string到底被誰持有著?

> gcroot -all 00007f6ad09421f8

Thread 3f68:
    00007F6795BB58A0 00007F6C1D7D0745 System.Diagnostics.Tracing.CounterGroup.PollForValues() [/_/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/CounterGroup.cs @ 26NDaXl0]
        rbx:  (interior)
            ->  00007F6BDFFFF038 System.Object[]
            ->  00007F69D0033570 testwebapi.Controllers.Processor
            ->  00007F69D0033588 testwebapi.Controllers.CustomerCache
            ->  00007F69D00335A0 System.Collections.Generic.List`1[[testwebapi.Controllers.Customer,DiagnosticScenarios]]
            ->  00007F6C000148A0 testwebapi.Controllers.Customer[]
            ->  00007FNDaXl6AD0942258 testwebapi.Controllers.Customer
            ->  00007F6AD09421F8 System.String

HandleTable:
    00007F6C98BB15F8 (pinned handle)
    -> 00007F6BDFFFF038 System.Object[]
    -> 00007F69D0033570 testwebapi.Controllers.Processor
    -> 00007F69D0033588 testwebapi.Controllers.CustomerCache
    -> 00007F69D00335A0 System.Collections.Generic.List`1[[testwebapi.Controllers.Customer,DiagnosticScenarios]]
    -> 00007F6C000148A0 testwebapi.Controllers.Customer[]
    -> 00007F6AD0942258 testwebapi.Controllers.Customer
    -> 00007F6AD09421F8 System.String

Found 2 roots.

從string的引用鏈看,它是被 CustomerCache 所持有,然後就可以到程式碼中尋找問題啦。

原文連結:https://docs.microsoft.com/en-us/dotnet/core/diagnostics/debug-memory-leak

總結

到此這篇關於教你如何排查 .NET 記憶體洩漏的文章就介紹到這了,更多相關排查 .NET 記憶體洩漏內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!