Problem Description: Adding an ActiveX control, such as Axcanlendar, to a Windows Form, explicitly releasing the control's resources, and clearing a reference to it, the control still cannot be reclaimed by GC.
--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------
Problem Recurrence: Add a Axcanlendar control and a button to the form. The Code for the button click is as follows:
private void Button1_Click (object sender, EventArgs e)
{
This. Controls.remove (THIS.AXCALENDAR1);
WeakReference wr = new WeakReference (this.axcalendar1, false);
Axcalendar1.dispose ();
Marshal.ReleaseComObject (Axcalendar1.getocx ());
AXCALENDAR1 = null;
int i = 0;
while (WR. IsAlive)
{
i++;
Gc. Collect ();
MessageBox.Show (i.ToString ());
}
}
--------------------------------------------------------------------------------------------------------------- -----------
Problem analysis:. NET's GC is a reference to determine whether a resource can be recycled, for unmanaged resources, we generally need to explicitly call its Dispose or close functions to free unmanaged resources. But when we explicitly invoke the Axcanlendar dispose function to dispose of the resource and set it to NULL, the GC is still unable to reclaim it, indicating that it is still referenced by a variable. So what is it that references it. We can easily view its roots using WinDbg.
0:009>!dumpheap-type Axmsacal.axcalendar
Loading The heap to our cache.
Address MT Size
012c94f8 00978424 336 2 axmsacal.axcalendar
0:009>!gcroot 012c94f8
esp:12e5fc:root : 012c8bd8 (Windowsapplication4.form1)->
012cbc78 (System.Windows.Forms.LayoutEventArgs)->
012c94f8 (Axmsacal.axcalendar)