1. 程式人生 > >.NET中的記憶體分析

.NET中的記憶體分析

.NET中的記憶體洩漏分析

本文簡單介紹常見的記憶體分析工具

託管資源和非託管資源

  • 託管資源:CLR管理分配和釋放的資源,主要是指託管堆上分配的記憶體資源。應用建立的大多數物件是託管資源嗎,可由.NET的垃圾回收器來管理記憶體。
  • 非託管資源: 不受CLR管理的物件,如Windows作業系統核心物件,包括檔案,視窗,網路連線,資料庫連線等。

在託管程序中存在兩種記憶體堆:本機堆 ( Native Heap ) 和託管堆(Managed Heap )。其中 本機堆 用於非託管程式碼所需記憶體,託管堆 為所有 .NET託管物件 分配記憶體,也叫 GC堆
如果使用了非託管資源,當不再需要此資源時,需要手動清理。

示例程式碼

在一個父窗體開啟一個子窗體,子窗體載入時建立一個帶背景圖的按鈕和一個PictureBox

父窗體

private void btnOpenChild_Click(object sender, EventArgs e)
{
    Child child = new Child();
    child.ShowDialog();
    child.Dispose();
}

子窗體

private void Child_Load(object sender, EventArgs e)
{
    AddButton();
    pictureBox1.Image = Properties.
Resources.sam_trotman_758969_unsplash; } private void AddButton() { // Create a button and add it to the form. Button button1 = new Button(); // Anchor the button to the bottom right corner of the form. button1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right); // Assign a background image.
button1.BackgroundImage = Image.FromFile($"{AppDomain.CurrentDomain.BaseDirectory}images//sam-trotman-758969-unsplash.jpg"); // Specify the layout style of the background image.Title is the default. button1.BackgroundImageLayout = ImageLayout.Stretch; // Specify the size of the button. button1.Size = new Size(200, 100); // Set the button's TabIndex and TabStop properties. button1.TabIndex = 1; button1.TabStop = true; // Add a delegate to handle the Click event. button1.Click += new EventHandler((object sender, EventArgs e) => { MessageBox.Show("Hi."); }); // Add the button to the form. this.Controls.Add(button1); } private void Child_FormClosing(object sender, FormClosingEventArgs e) { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); pictureBox1.Image = null; } foreach (var control in this.Controls) { if (control.GetType().Name == nameof(Button)) { var btn = (Button)control; if (btn.BackgroundImage != null) { btn.BackgroundImage.Dispose(); btn.BackgroundImage = null; } } } }

記憶體分析

如下圖(visual studio中的診斷工具):Process Memory,同性能分析工具中的Private Memory,指程序可執行檔案要求的記憶體量,不一定是程序的實際使用量。Private Bytes是程序使用的記憶體量的合理近似值,可以幫助排查記憶體洩漏問題。比如,當您發現此數值一直在不斷增長,可以猜想記憶體是否發生了洩漏。
圖1

當然也可使用visual studio中的效能分析器進行分析,如下
效能分析器-1

可進行快照
在這裡插入圖片描述

Windows系統上還有其他分析工具,比如效能監視器Process Explorer 等。關於Process Explorer可參考此文章,文章中已包含下載地址。如下圖,是Process Explorer對本文例項程式碼的記憶體分析。
Process Explorer

以下是效能監視器 (輸入perfmon開啟) 對本文示例程式碼的分析
效能監視器

參考