[RESOLVED] Question about Using PenSoandSo ... End Using
I have a large application that has numerous places where I define pens using code like this :
Code:
MyPen = New Pen(Color.FromArgb(Red , Green, Blue), ws)
If I define the pens in one place and then afterward use :
Code:
Using MyPen
Graphics.FromImage(bmp).DrawLine(MyPen, p1, p2)
End Using
is that ok or should I instead define the pen right where I have Using like this :
Code:
Using MyPen = New Pen(Color.FromArgb(Red , Green, Blue), ws)
Graphics.FromImage(bmp).DrawLine(MyPen, p1, p2)
End Using
If it doesn't make any difference then I can save myself an enormous amount of work but if there is a very good reason to do it like the code immediately above shows then I can make the conversion. My application is working just fine the way it is now and I'm not using "Using ... End Using" at all but I'm guessing that my application may be using up more system resources if I'm not using "Using ... End Using". It would be nice if the code :
Code:
Using MyPen
Graphics.FromImage(bmp).DrawLine(MyPen, p1, p2)
End Using
is just as efficient where I first define the pen in one place and then draw with the Using ...End Using block.
Re: Question about Using PenSoandSo ... End Using
If you aren't disposing your Pens then you have a big resource leak, so you definitely do need to do something.
The point of a Using block is to define a scope so it doesn't really make sense to create the object outside of that scope, but it is legal so you can do it if it saves you a lot of effort. In future though, I suggest that you use the pattern from your third code snippet.
Re: [RESOLVED] Question about Using PenSoandSo ... End Using
Am I correct in believing that this:
Code:
Using MyPen = New Pen(Color.FromArgb(Red , Green, Blue), ws)
Graphics.FromImage(bmp).DrawLine(MyPen, p1, p2)
End Using
can exactly be replaced by this?
Code:
Graphics.FromImage(bmp).DrawLine(New Pen(Color.FromArgb(r, g, b), ws), p1, p2)
I admit it gives a rather long line, and I'm cheating a bit by using r, g and b instead of Red, Green and Blue. But if you have a lot of these lines, it might make the code a bit less cluttered. BB
Re: [RESOLVED] Question about Using PenSoandSo ... End Using
No you are not correct. What is the point of the Using block? It's to Dispose the object whose scope it defines. That second code snippet not only doesn't Dispose the Pen, it doesn't keep a reference to it so it couldn't Dispose it even if it wanted to.
What's more, which I didn't notice at first, your're calling Graphics.FromImage to create a Graphics object and you're not Disposing that either, so your resource leak is even worse. You MUST Dispose every object that supports it when you are done with it. You should be using two Using blocks: one for the Pen and one for the Graphics:
vb.net Code:
Using MyPen As New Pen(Color.FromArgb(Red , Green, Blue), ws)
Using g = Graphics.FromImage(bmp)
g.DrawLine(MyPen, p1, p2)
End Using
End Using