Is object eligible for garbage collection if it's created within using-statement and not explicitly bound to a reference?

StackOverflow https://stackoverflow.com/questions/16216765

  •  13-04-2022
  •  | 
  •  

質問

I have this (illustration only) C# code:

using( new System.IO.MemoryStream() ) {
    System.Threading.Thread.Sleep(1000);
}

Note that here a MemoryStream is created and not explicitly bound to a reference. So unless there's some special treatment because of the using statement the object has no references to it and could be collected before control leaves the using statement and maybe even before Sleep() completes.

Is MemoryStream eligible for collection before control leaves the using statement?

役に立ちましたか?

解決 2

No, it is NOT.

Behind the scenes, a hidden reference to the MemoryStream has been created, so it is still alive.

他のヒント

No.

The using statement compiles to a finally block that disposes the object.

Thus, it is still in scope until the end of the block.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top