我知道以下语句对于垃圾收集很有用。 实际上,它必须与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.
更多推荐
发布评论