Does “using” statement always dispose the object?

后端 未结 3 906
渐次进展
渐次进展 2020-12-16 10:04

Does the using statement always dispose the object, even if there is a return or an exception is thrown inside it? I.E.:

using (var myClassInsta         


        
3条回答
  •  余生分开走
    2020-12-16 10:50

    No it doesn't.

    But that's not the fault of using statement though. It's because how the finally blocks are handled by CLR. There ARE some cases that finally blocks will not execute. If you have an unhandled exception and if the CLR thinks that executing more code will lead to more errors, it will not execute Dispose method (because it will not execute the finally block which Dispose method is compiled down to..). Therefore, be very careful and don't put your life into the execution of Dispose method.

    The other cases which can cause Dispose method not being executed can be listed as:

    • Environment.FailFast

    • OutOfMemoryExceptionand StackOverflowException

    • Killing the process

    • Power loss

提交回复
热议问题