Search code examples
c#garbage-collectiondisposeidisposable

How certain types like Image can be Dispose using the Dispose() method


Let's say I have a large Image object, if I call the Dispose() method of this object I can easily see the memory consumption of my application be reduced, since I just cleared the object from memory.

But what if I have my own type/class and want to dispose an instance of it, which, let's say, contains a byte[] array (which I think is the same thing the Image class has internally). How would I go about implementing IDisposable so when Dispose() is called the byte[] is instantly disposed from memory. Without me having to wait for GC?

What if it were a string instead of a byte[]?


Solution

  • Memory consumption reduces in two cases:

    1. Garbage collector has freed up the memory, and
    2. Unmanaged code was executed which has freed up the memory instantaneously.

    Image data example is the second case. Images are held by OS and when you dispose an image, operating system is called to free the image buffer. This is operating system's job because operating system is the one to render images on the screen, which then depends on hardware and drivers. In addition to this, graphical operating system is extremely optimized to work with image data - no wonder then that it is used to work with images when needed.

    It is completely opposite when you create your own disposable class. Executing dispose actually does nothing, regarding the memory footprint. Even garbage collecting won't reduce the memory usage as long as there is a live pointer pointing to the disposed class.

    Class should implement IDisposable only if it allocates some unmanaged resources - file handles, images, sockets (which are only a kind of file handles from OS point of view), etc. Dispose method is supposed to free up only the unmanaged resources. There is no point in setting the fields to null and do similar silly things.