How are objects of an object of an object of a .NET object located, unless you explicitly call Dispose on them?

When writing a small rice application (for myself), I initially wrote the following code in the onClick handler:

g.DrawEllipse((new Pen(pencolour, penSize)), eX, eY, 1, 1); 

which I later changed to

 Pen pen1 = new Pen(pencolour, penSize); g.DrawEllipse(pen1, eX, eY, 1, 1); pen1.Dispose(); 

My question is: are two parts of the code equivalent, or does the first create Pen objects that are never deleted?

+4
source share
4 answers

They are deleted when the garbage collector starts and determines that the object is no longer in use. It’s better to dispose of the objects themselves, so resources are immediately freed.

Also consider using the using statement:

 using (Pen pen1 = new Pen(pencolour, penSize)) { g.DrawEllipse(pen1, eX, eY, 1, 1); } 

This automatically removes the Pen, even if DrawEllipse throws an exception, and the IDE ensures that pen1 is accessible only from the usage block.

+7
source

How Pen implements IDisposable is best used with instructions to ensure that Dispose is called.

 using (Pen pen1 = new Pen(pencolour, penSize)) { g.DrawEllipse(pen1, eX, eY, 1, 1); } 

If you do not, pen1 will be GC-ed later, since it will not be used after exiting the area.

+4
source

The first creates Pen objects that are never deleted. Ultimately, they will be GC'd, but they will temporarily leak any unmanaged resources that wrap Pen.

0
source

Of course, this method is not called by the DrawEllipse method, so the two fragments do not match.

0
source

Source: https://habr.com/ru/post/1395290/


All Articles