Does the used block guarantee that the object will not be deleted until the end of the block?

I know that the using block ensures that the IDisposable object will be used at the end of the block, but does it guarantee that the object will not be deleted before then?

In other words, if I have:

 using (new DisposableObject()) { // blah blah } 

Can I be sure that DisposableObject will not be placed until the end of the block, or can the garbage collector detect that I do not have a handle to it inside the block and delete it right away?

+4
source share
3 answers

Your object will be deleted only once and will not be GC'd until the end of the used block.

The specification guarantees that if you have using (expression) statement and the type of the expression is a type with a null value (call it ResourceType ), it will be decomposed into:

 { ResourceType resource = expression; try { statement; } finally { if (resource != null) ((IDisposable)resource).Dispose(); } } 

Dispose will be called once at the end of the block, and there is a local generation that keeps a reference to your one-time object. Local prevents the object from being GC'd until the end of the used block.

+4
source

No no. Nothing bothers you:

 using(var myObject = new DisposableObject()) { myObject.Dispose(); } 

What exactly happens in this case depends on the semantics of DisposableObject . This may throw an exception, or it may be completely happy that Dispose is called twice.

It should be noted that removing objects and garbage collection are completely different concepts. Just because the object is located does not mean that it will be collected by garbage, and just because the object was collected by garbage does not mean that it will be deleted.

An object can be garbage collected as soon as all references to the object are destroyed or inaccessible. This cannot happen when the code runs inside using -block, because the block itself has a reference to the object.

+6
source

I think that you would rather want to know about garbage collection rather than recycling.

The garbage collector will not collect the object inside the using block. Even if you specifically call the Dispose method, there is still an active link to it, so it will not be compiled.

The code generated for the using block ends with checking if the object can be deleted so that use will keep the object for the duration of the using block.

+2
source

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


All Articles