如何在ADO.NET对象上调用Dispose? [英] How is Dispose called on ADO.NET objects?
问题描述
实现 IDbConnection
, IDbCommand
和 IDataReader $ c的数据库访问类$ c>都实现了
IDisposable
,但是命令和读取器显然取决于Connection。我的问题是,我是否必须分别对每个这些对象都进行Dispose()处理,还是将Connection对象的处理也对其他对象进行处理?
The database access classes that implement IDbConnection
, IDbCommand
and IDataReader
all implement IDisposable
, but obviously the Command and the Reader are dependent on the Connection. My question is, do I have to Dispose() of each these objects individually or will disposing of the Connection object dispose of the others too ?
也就是说,我可以这样做并保证我不会冒任何未托管资源未被释放的风险:
That is, can I do this and guarantee I'm not risking leaving any unmanaged resources not being freed:
using (IDbConnection conn = GetConnection())
{
IDbCommand cmd = conn.CreateCommand();
cmd.CommandText = " ..... ";
IDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
}
}
还是我必须这样做:
using (IDbConnection conn = GetConnection())
{
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = " ..... ";
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
}
}
}
}
或者此实现取决于它,所以它可能
Or is this implementation dependent, so it would potentially work using one database's provider but not for another's ?
推荐答案
最好的策略是在使用块时使用所有ADO.NET对象。
Best policy is to use all ADO.NET objects in using blocks- full stop.
在各种ADO.NET对象上进行一点反射,即会发现,如果未关闭/处置,事物或多或少会掉在地上。这样做的效果在很大程度上取决于您使用的提供程序-如果您使用的是下面带有非托管句柄的内容(ODBC,OleDb等),则可能会泄漏内存,因为我什么也没看到以终结器的方式。如果它是一个全托管的提供程序(例如SqlClient),它将最终得到清理,但是根据您持有的对象,最终可能会使数据库服务器上的资源使用时间比您想要的长得多
A little Reflector-ing on various ADO.NET objects shows that things will more or less be dropped on the floor if not Closed/Disposed. The effect of that will depend a lot on which providers you're using- if you're using something with unmanaged handles underneath (ODBC, OleDb, etc), you're probably going to leak memory, as I didn't see anything in the way of finalizers. If it's an all-managed provider (eg, SqlClient), it'll eventually get cleaned up, but depending on which objects you're holding onto, you could end up keeping resources in use on the DB server a lot longer than you want.
这篇关于如何在ADO.NET对象上调用Dispose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!