Search code examples
c#.netdisposeidisposable

Dispose() - What call this and when


I have this piece of code:

using (var img = Bitmap.FromFile(path))
{
    result = new Bitmap(img);
}

Questions:

  1. Is the Bitmap instance immediately called at the end of the using? or is it waiting to be garbage collected?
  2. Is it disposed from the current thread or another?

Solution

  • You actually have two Bitmap instances - img and result.

    img will get disposed (I believe on the current thread) at the end of the using block. The compiler inserts a Dispose call in a finally block for you.

    result does NOT get disposed automatically - whatever consumes result will need to dispose of it.

    Also note that getting disposed and garbage collected are two different things - Dispose will clean up any unmanaged resources immediately (in the case of a Bitmap it will be the underlying graphics objects), but any managed resources will be garbage collected as some later, undetermined time.