Search code examples
c#.netgarbage-collectiondisposeterminate

Do IDisposable objects get disposed of if the program is shut down unexpectedly?


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.


Solution

  • 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.