基本情況
最近在做的一款程序,長時間運行總會出現(xiàn)莫名的問題。有時是自動關(guān)閉,有時程序報錯,有時調(diào)用的dll異?!?/p>
提出假設(shè)——dll內(nèi)存泄漏
由于開始與C++組合作時,使用其提供的dll出現(xiàn)過數(shù)據(jù)讀寫時異常(內(nèi)存操作異常),于是懷疑他們提供的dll有內(nèi)存泄漏。于是想通過日志或其它方法來確認這個猜測。
如何驗證是C++ dll的問題?
通過記錄當前Process的Memory情況,確認在調(diào)用dll時內(nèi)存的基本情況,然后與不調(diào)用dll的內(nèi)存情況進行比對,基本就能確認到底是不是dll的內(nèi)存操作有問題。
日志數(shù)據(jù)分析
記錄進程內(nèi)存情況與電腦內(nèi)存運行情況
以下為記錄內(nèi)存狀況的Function:
private static void MemoryLog()
{
Task.Run(async () =>
{
string appName = typeof(App).Namespace;
var mb = 1024 * 1024;
while (true)
{
Process currentProcess = Process.GetCurrentProcess();
var working = currentProcess.PagedMemorySize64;
await Task.Delay(1000);
NlogHelper.Logger.Trace($"MemoryLog Working Set: {currentProcess.WorkingSet64 / mb} MB, PeakWorking Set: {currentProcess.PeakWorkingSet64 / mb} MB, Private Memory: {currentProcess.PrivateMemorySize64 / mb} MB, PagedMemory: {currentProcess.PagedSystemMemorySize64 / mb}MB, PeakPagedMemory:{currentProcess.PeakPagedMemorySize64 / mb}MB");
NlogHelper.Logger.Trace($"MemoryLog {Performance.GetMemInfo()}");
}
});
}
上述代碼中,working memory為進程分配的物理內(nèi)存,private memory為進程的專用內(nèi)存(此為最關(guān)鍵,虛擬內(nèi)存),詳細參考API:Process 類 (System.Diagnostics) | Microsoft Learn
下述為Performance中的GetMemInfo方法:
public static string GetMemInfo()
{
MEMORY_INFO mi = GetMemoryStatus();
return string.Format(", \t\t\t{0},{1:f0}%", FormatSize(mi.ullTotalPhys - mi.ullAvailPhys), mi.dwMemoryLoad);
}
/// <summary>
/// 獲得當前內(nèi)存使用情況
/// </summary>
/// <returns></returns>
public static MEMORY_INFO GetMemoryStatus()
{
MEMORY_INFO mi = new MEMORY_INFO();
mi.dwLength = (uint)Marshal.SizeOf(mi);
GlobalMemoryStatusEx(ref mi);
return mi;
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);
注意:在記錄日志時最好記錄為一行,同時數(shù)據(jù)之間以空格或逗號或tab分離等分隔符分離,以方便數(shù)據(jù)分析時在表格中使用分隔符進行分列統(tǒng)計。
日志圖表化
通過日志記錄發(fā)現(xiàn),專用內(nèi)存在不斷增長:
也就是說一定是存在內(nèi)存泄漏了。
而在不調(diào)用dll時運行50次的內(nèi)存情況則如下:
也就是說在程序運行期間內(nèi)C#內(nèi)存使用情況是基本穩(wěn)定的,不會出現(xiàn)不斷增長的情況。文章來源:http://www.zghlxwxcb.cn/news/detail-812348.html
以上基本可以確認是C++的dll出現(xiàn)了問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-812348.html
到了這里,關(guān)于C#調(diào)用C++ dll異常排查的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!