. Net Memory leakage:
Reference not eliminated, event not deleted
If it is a WPF application, there are common problems with the release of Image objects. The attributes of objects bound to non-dependent attributes or that do not implement the INotifyPropertyChanged interface are not described here.
This article describes how to use the powerful. Net Memory Profiler to analyze. Net application Memory leakage. The Demo is to use mdbg.exe to debug the Demo in the. net program.
Sample Code:
Namespace MemLeakProfileDemo
{
Public partial class Form1: Form
{
Private Fool fool;
Private FoolBrother brother;
Public Form1 ()
{
InitializeComponent ();
Fool = new Fool ();
Brother = new FoolBrother ();
// Reference fool
Brother. YoungFool = fool;
}
Private void btnAlloc_Click (object sender, EventArgs e)
{
Var I = 10;
// AllocalHugeMem will apply for 10 MB of memory
Fool. AllocalHugeMem ();
}
Private void btnWrongRelease_Click (object sender, EventArgs e)
{
// Although fool points to null, brother retains the reference to fool, and GC is ineffective. Memory leakage
Fool = null;
GCRelease ();
}
Private void btnRightRelease_Click (object sender, EventArgs e)
{
// Eliminate the reference of brother to fool, and the GC effect is obvious.
Fool = null;
Brother = null;
GCRelease ();
}
Private void GCRelease ()
{
GC. Collect ();
GC. WaitForPendingFinalizers ();
GC. Collect ();
}
}
Public class Fool
{
Private IList <byte []> list = new List <byte []> ();
Public void AllocalHugeMem ()
{
Var buffer = new byte [10*1024*1024];
For (int I = 0; I <buffer. Length; I ++)
{
Buffer [I] = 1;
}
List. Add (buffer );
}
}
Public class FoolBrother
{
Public Fool YoungFool
{
Get;
Set;
}
}
}
- Start Demo.exe using. Net Memory Profiler,
- Capture a Snapshot first (Collect Snapshot)
- Multiple clicksAllocal MemButton, apply for memory, and then clickWrong Release MemButton. capture another snapshot.
At this point:
// Although fool points to null, brother retains the reference to fool, and GC is ineffective. Memory leakage
Fool = null;
GCRelease ();
Because a FoolBrother object strongly references the fool object, the fool object cannot be GC. with powerful tools, we can intuitively see that:
One Fool object instance is not released. Double-click the row to view it:
We can see that the reference count of this object is 1, GC Age, and the right side is the stack for creating this object.
Double-click the Instances row. A clear reference relationship diagram is displayed:
Everything is ready!
ClickRight Release MemButtonFoolBrotherClear the object, capture the snapshot, and compare the effect.
This Demo will show you how to use the Windbg SOS extension to find out memory leaks.