Skip to content
fremag edited this page Dec 3, 2016 · 3 revisions

Some types allocate unmanaged ressources and need to be disposed explicitly so they inherits the IDisposable interface. This can be done by calling the Dispose method or a "using" block.

Let's have a look at this code:

public class MyDisposableType : IDisposable
{
    IntPtr hglobal = Marshal.AllocHGlobal(100000);

    public void Dispose()
    {
        Marshal.FreeHGlobal(hglobal);
    }
}

This type will allocate an unmanaged memory area that is freed only by the Dispose method.

In the MemoDummy script, N instances are created but are referenced so they should be garbage collected but they're not.

public override void Run()
{
    for(int i=0; i < N; i++)
    {
        MyDisposableType obj = new MyDisposableType();
    }
    System.GC.WaitForFullGCComplete();
}

Let's dump this and have a look at it:

There are 300 instances of "MyDisposableType" and none of them is referenced (see "RefIn" column with 0), even if we lok at the details of one of them, there is no reference on it and it's not garbae collected so we have a memory leak...