Properly Using Dispose

ALX

Well-known member
Joined
Nov 16, 2005
Messages
230
Location
Columbia, SC
Programming Experience
10+
I apologize for asking such basic questions. There are things that get missed when you learn this stuff from a book without any formal guidance. You folks ARE my formal guidance. So this question has to do with using Dispose to avoid locks on files and memory leaks.
Code:
        bmp = New Bitmap("somegraphicfile.bmp")
        bmp1 = New Bitmap(somewidth, someheight)
        bmp2 = New Bitmap(somewidth, someheight)

        g = Graphics.FromImage(bmp1)
        g.DrawImage(bmp, 0, 0, somewidth, someheight)               '   Draw bmp to bmp1
        bmp.Dispose()                                               '   Release the lock on "somegraphicfile.bmp"
        g.Dispose()                                                 '   Does this also release the lock on the file ?

        g = Graphics.FromImage(bmp2)
        g.DrawImage(bmp1, 0, 0, somewidth, someheight)              '   Draw bmp1 to bmp2

        '   Does g need to be Disposed before reassigning g to another Graphics object or 
        '   can I wait until I've completed the tasks and then Dispose g at the end ?

        bmp = New Bitmap(somewidth, someheight)
        g = Graphics.FromImage(bmp)
        g.DrawImage(bmp1, 0, 0, somewidth, someheight)              '   Draw bmp1 to bmp

        g.Dispose()
There are a couple questions embedded in the comments in the code above that have puzzled me for a long time and I'm finally getting around to trying to iron these things out in my head.
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,412
Location
Norway
Programming Experience
10+
g.Dispose() ' Does this also release the lock on the file ?
No, it disposes the managed Graphics object and also releases unmanaged GDI+ resources associated with this object. It is the bmp.Dispose call that releases the file, since it was loaded from a file.
Does g need to be Disposed before reassigning g to another Graphics object or
Yes. If g references an object and you assign a new object to g, then you no longer have reference to first object, so that object will remain in memory and is not disposed until garbage collector (GC) does automatic cleanup, and that can take a while. In the mean time, if you use lots of GDI objects you could run out of system resources.
 
Top Bottom