none
Dispose. Is Bitmap managed resoure ?

    Question

  • I implement IDisposable interface
    http://msdn2.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx

    1. So i have Bitmap GDI + variable viewBuffer.
    Is it managed object ? But if it is true, why it has dispose method ?
    protected virtual void Dispose(bool disposing) 
    {
    if (disposing)
    {
    // Free other state (managed objects).
    }
    // Free your own state (unmanaged objects).
    // Set large fields to null.
    }

    So i place it to managed section

    protected virtual void Dispose(bool disposing)
    {
    if (disposing)
    {
    this.viewBuffer.Dispose();
    }
    // Free your own state (unmanaged objects).
    // Set large fields to null.
    }

    2. In my class constructor i use following code

    if (this.hMap != 0)
    CloseMap();

    but if i set

    public void CloseMap()
    {
    Dispose();
    }

    As i can undestand GC.SuppressFinalize(this); will be executed and my object will be marked to deleted.

    So in my case it is bad code. Is it true ?

    public void CloseMap()
    {
    Dispose();
    }



    Monday, April 14, 2008 1:41 PM

Answers

  • Yes, Bitmap is a managed class.  But it is a very thin wrapper around code in gdiplus.dll, the unmanaged code that implements GDI+.  Bitmap data is allocated in unmanaged memory.  To ensure this memory gets released as soon as possible, the Bitmap's base class (Image) has a Dispose() method.  And a finalizer to ensure that memory is released when the client code doesn't call Dispose().  Calling Dispose() for bitmaps is pretty important because the Bitmap class is so small.  You can create a *lot* of Bitmaps before the garbage collector kicks in, running the risk you'll run out of available unmanaged memory.

    If you have a Bitmap member in your class, you should indeed also provide a Dispose() method.  You'd simply call the member's Dispose() method, as you do.  You do NOT need a finalizer since your own class does not have any unmanaged resources that need to be released.  The finalizer of the Bitmap member is sufficient.  Since you don't have a finalizer, you don't have to worry about GC.SuppressFinalize().

    I don't understand why you'd call CloseMap/Dispose() in the constructor.  If the bitmap is just a temporary variable instead of a class member, you'd just call Dispose() on it when you're done using it.
    Tuesday, April 15, 2008 2:50 AM