active said:
I did the following and then wondered it's good practice.
Me.CreateGraphics.DrawImage(Img, 0, 0)
I'm thinking about disposing the Graphics object.
You are right in your concerns about the disposing. You should
definitely keep a reference to the object so that you can dispose it:
Dim g As Graphics = Me.CreateGraphics
g.DrawImage(Img, 0, 0)
g.Dispose
A couple of lines after this I exit the sub so I wonder if it'll get
disposed automatically?
When there is no reference to the object any more, it's up for garbage
collection. However, as you haven't disposed the object, it's still in
the finalizer queue. This means that the garbage collector can not free
the object, but instead have to move it to the next heap generation and
wait for a background thread to finalize it. After finalizing, the
garbage collector can free the object.
If you call the Dispose method, the object will be removed from the
finalizer queue. This means that the garbage collector can free the
object at the next garbage collection.
Also, the graphics object contains a handle to a windows graphics object
which you should release by calling Dispose. Otherwise the object will
hold on to the handle until it's finalized, and you risk to run out of
windows resources.
Should the above structure be avoided?
Definitely.
In general, if an object is such that it should be disposed and the
reference goes out of scope, say by a sub ending, is it necessary to
explicitly dispose the object?
Not strictly neccesary, as the finalizer will eventually do that, but
your program will use less resources and put less stress on the memory
management if you do.
I had once believed that to be true, now I'm wondering if I should be
reviewing all my code to see if I left any thing undisposed that I shouldn't
have.
If you have relied on the finalizer to dispose your objects in the past,
I think that it's a good idea to review the code.