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

前端 未结 6 1696
借酒劲吻你
借酒劲吻你 2021-01-17 07:31

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 t

6条回答
  •  感情败类
    2021-01-17 08:14

    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.

提交回复
热议问题