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!
If the class inherits from a class that implements IDisposable it must call the Dispose(), or Dispose(bool) method of the base class from within its own implementation of Dispose() or Dispose(bool), respectively. This ensures that all resources from the base class are properly released.
Rule#1: Properly dispose of classes that implement IDisposable. The first rule is whenever you are consuming a class that implements the IDisposable interface; you should call the “Dispose” method when you are done with that class.
C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.
The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
using (SomeDisposableResource resource = new SomeDisposableResource())
{
// TODO: use the resource
}
is equivalent to:
SomeDisposableResource resource = new SomeDisposableResource();
try
{
// TODO: use the resource
}
finally
{
if (resource != null)
{
((IDisposable)resource).Dispose();
}
}
so, up to you to draw conclusions. Everything depends on how you define immediate. In a multithreaded environment other actions could be performed between the try
block and the disposal of the resource but as it is wrapped in a finally
block it is guaranteed that the Dispose method will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With