As describe this article, about usage of using on IDisposable objects, it says one interesting words:
…using block, the Dispose method is automatically called sometime after the block ends. (It may not be immediate; it depends on the CLR.)
Interesting here is “It may not be immediate; it depends on the CLR“.
Can anyone provide more details on this? Because we have some strange situations where it seems that on code using(new MyDisposable()) {…}, after end of block } it does NOT immediately calls Dispose method on MyDisposable instance, but some time later.
UPDATE: Conclusion for me, it seems to me that i have problem elsewhere. I think that Dispose method can be called some time later after using block ends. But when it is not like that, than i must find problem somewhere else in my code.
Thanks for responses!
I’m a little skeptical of that statement, and think they meant something else (perhaps garbage collection). A using statement is just syntactic sugar for a try/finally block where the finally block calls dispose. Given this C#:
The IL looks like this:
Notice on the last line it’s just a .try and .finally. This is also indicated in The using statement from the C# spec.