It has been seen before that managed code will not cause a memory leak. I'm not very knowledgeable about GC, but I do agree that managed code does not generate a memory leak unless you are not releasing unmanaged resources correctly.
Today I see a very interesting example of a memory leak caused by a handler that does not release events.
The idea of releasing handler has not been in the past, mainly because of the lack of awareness of this aspect, not to develop good habits. Only know when care about this event to register, temporarily do not care about the removal. It never occurred to me that the eventual removal of unnecessary handler would result in this class not being recycled properly, resulting in unnecessary memory wastage.
The thing is, today when I look at project source code, I find an interesting word: "WeakEvent". I used to know a little about weakreference, so I was curious to see what it was.
It is found to be a delegate implemented through weak references. Because there are not too many annotations, all of them do not know why they encapsulate the event in this way. So I Google a bit and found a very interesting article about weak event.
The article raises a question as follows:
unrelease Event Handler
using System;
using System.Collections.Generic;
using System.Text;
Using Microsoft.Win32;
Namespace ConsoleApplication16
{
class Displaysettingslistener
{
byte[] M_extramemory = new byte[1000000];
Public Displaysettingslistener ()
{
Systemevents.displaysettingschanged + = new Eventhand Ler (ehdisplaysettingschanged);
}
private void Ehdisplaysettingschanged (object sender, EventArgs e)
{
}
}
Class program
{
static void Displaymemory ()
{
Console.WriteLine, "Total Me Mory: {0:###,###,###,# #0} bytes ", GC. Gettotalmemory (true));
}
static void Main ()
{
displaymemory ();
Console.WriteLine ();
for (int i = 0; i < 5; i++)
{
Console.WriteLine ("---New Listener #{0}---", i + 1) ;
DisplaysettiNgslistener listener = new Displaysettingslistener ();
Listener = null;
GC. Collect ();
Displaymemory ();
}
Console.read ();
}
}
}
The results of the operation are as follows: