When are C# “using” statements most useful?

后端 未结 14 1919
没有蜡笔的小新
没有蜡笔的小新 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:46

    When the method exits, wont the Font object be disposed of anyway?

    No, it will become unreferenced, and thus eligible for garbage collection. Unless something else (e.g. a reference held in another data structure) holds on to a reference.

    Or does the Dispose method get run at another time after the method exits?

    Yes, in a process not allocating much memory that could be a considerable time after the method has exited.

    Garbage Collection is inherently asynchronous and lazy, thus making it a great way to ensure memory is freed, if memory is not too limited; but poor for almost any other resource.

提交回复
热议问题