When are C# “using” statements most useful?

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

    Without using (or manually calling Dispose()), the object will eventually be disposed of, just not at a deterministic time. That is, it can happen straight away, in two days' time, or (in some cases) never.

    For things like, say, network connections, you want the connection to close when you're done with it, not "whenever", otherwise it'll idle around hogging up a socket.

    Further, for things like mutex locks, you do not want those to be released "whenever", or else deadlock is likely to result.

提交回复
热议问题