What happens if the program exits unexpectedly (either by exception or the process is terminated)? Are there any situations like this (or otherwise) where the program will terminate, but IDisposable
objects won't be properly disposed of?
The reason I'm asking is because I'm writing code that will communicate with a peripheral, and I want to make sure there's no chance it will be left in a bad state.
If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().
IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.
Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.
You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope. Yes, you should dispose of objects that implement IDisposable.
If the cause is an exception and thrown from within a using
block or a try catch finally
block, it will be disposed as it should. If it is not catched by a using
block it is not disposed automatically (like it doesn't do when the application closes properly).
A sample:
IDisposable d1 = new X(); using (IDisposable d2 = new X()) { throw new NotImplementedException(); } d1.Dispose();
d1
is not disposed, d2
usually is. Some types of exceptions may prevent handling of using
blocks and also some program crashes. If the cause is a power failure or system crash, there is nothing you can do either of course.
If the program quits unexpectedly (for example you kill the process) there are absolutely no guarantees that the IDisposable.Dispose
method will be called. You'd better not rely on it for such events. The Dispose method must be called manually by your code, it's not something that the CLR will call automatically for you.
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