When are C# “using” statements most useful?

后端 未结 14 1914
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 05:33

So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?

But when is this necessary/benef

14条回答
  •  终归单人心
    2021-02-13 05:45

    The using construct enforces deterministic disposal -- i.e. release of resources. In your example above, yes, if you don't employ a "using" statement, the object will be disposed, but only if the recommended disposable pattern (that is, disposing of resources from a class finalizer, if applicable) has been implemented for the class in question (in your example, the Font class). It should be noted, that the using construct can only be used with objects that implement the IDisposable interface. It is the presence of that interface on an object that allows using to "call" the Dispose method.

    Additionally, underlying resources will only be released when the garbage collector decides to collect your out-of-scope Font object. A key concept in .Net programming (and most languages with a garbage collector) is that just because an object goes out of scope does not mean that it is finalized/released/destroyed, etc. Rather, the garbage collector will perform the clean-up at a time it determines -- not immediately when the object goes out of scope.

    Finally, the using statement "bakes in" a try/finally construct to ensure that Dispose is called regardless of contained code throwing an exception.

提交回复
热议问题