Disposable Types

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()

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();

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...

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.