使用语句

编程入门 行业动态 更新时间:2024-10-14 10:39:35
使用语句 - 这比sql适配器更适合sql连接吗?(Using statement - is this more useful for the sql connection than the sql adapter?)

我知道以下语句对于垃圾收集很有用。 实际上,它必须与Try / Catch / finally相同。 如果我使用它的SQL连接,我应该还嵌套一个SQL适配器的进一步“使用”语句? 然后进一步嵌套使用DataSet?

using() { }

这个问题的另一个补充是,如果我想在多个方法中使用相同的连接,那么在每个方法中使用'()'还是我可以只创建一次这个连接对象?

I know that the following statement is useful for garbage collection. Effectively it must be the same as Try/Catch/finally. If I use it for the sql connection should i also nest a further 'using' statement for a sql adapter? And then a further nested using for the DataSet?

using() { }

A further addition to the question is if I want to use the same connection across several methods then is it best practice to have 'Using()' in each of the methods, or can I just create this connection object once?

最满意答案

是的,您应该使用using语句来处理实现IDisposable所有内容。 using语句并不是关于垃圾回收,而是关于资源(内存除外)。 DataSet和SqlDataAdapter都是IDisposable实例。

using块意味着您保证该对象所持有的资源以及时,确定的方式进行处理。 如果没有using ,这些资源何时会被释放并不能保证。 这可能会导致资源泄漏,例如文件句柄耗尽。

Yes, you should use the using statement to dispose everything that implements IDisposable. The using statement is not really about garbage collection, it's about resources (other than memory). Both DataSet and SqlDataAdapter are instances of IDisposable.

The using block means that you guarantee that the resources that the object holds are disposed in a timely, deterministic manner. Without using, there is no guarantee when these resources will be freed. This can lead to resource leaks, such as running out of file handles.

更多推荐

本文发布于:2023-07-07 21:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!