为什么反正叫SqlClient.SqlDataReader Close()方法? [英] Why call SqlClient.SqlDataReader Close() method anyway?

查看:140
本文介绍了为什么反正叫SqlClient.SqlDataReader Close()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时的SqlClient.SqlDataReader .NET托管对象或不是? 为什么我们必须显式调用Close()方法关闭打开的连接? 不应该运行的范围这样一个对象自动关闭呢? 如果没有垃圾收集清理呢?

Is the SqlClient.SqlDataReader a .NET managed object or not? Why do we have to call the Close() method explicitly close an open connection? Shouldn't running out of scope for such an object automatically close this? Shouldn't garbage collector clean it up anyway?

请帮助我了解什么是最好的做法在这里。

Please help me understand what is the best practise here.

我已经看到了相关的问题<一href="http://stackoverflow.com/questions/247311/sqldatareader-in-this-scenario-will-the-reader-get-closed">here并进一步说明了问题,我有一个Web应用程序。问题是,我们正在运行的连接。详细的错误是在这里:

I have seen a related question here and it further illustrates the issue I have with a web application. The issue is that we were running out of connections. The detailed error is here:

Exception: System.InvalidOperationException
Message: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Source: System.Data 

at  System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction)
at  System.Data.SqlClient.SqlConnection.Open()

要解决这个问题,我必须明确地关闭所有SqlDataReader的对象。

To fix this, I had to explicitly close all the SQLDataReader objects.

我使用的.NET Framework 3.5

I am using .NET Framework 3.5

推荐答案

当然,这时会超出范围收集(如果他们没有其它引用)。当它被收集,它将通过其Dispose()方法被关闭。但是,你永远不会真正知道当GC是要释放的东西;如果你不关闭你的读者,你很快用完可用连接到数据库中。

Sure, it will be collected when it goes out of scope (if their are no other references to it). When it is collected, it will be closed through its Dispose() method. However, you never really know when the GC is going to deallocate things; if you don't close your readers, you very quickly run out of available connections to the database.

  • O'Reilly's ADO.NET Connection Pool Explained
  • Microsoft's Retrieving Data using a DataReader has a general overview of DataReaders.

〜威廉·赖利陆

这篇关于为什么反正叫SqlClient.SqlDataReader Close()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆