简体   繁体   English

数据读取器在命令中使用语句

[英]Data reader in command using statement

I have a legacy system that I have noticed the following code in 我有一个旧系统,我注意到以下代码

var dataTable = new DataTable();
using(var connection = new SqlConnection())
using(var command = connection.CreateCommand())
{
     command.commandType = CommandType.StoredProcedure;
     //Attach command parameters etc. 
     var reader = command.ExecuteReader();
     dataTable.Load(reader);
}
return dataTable;

Normally I would wrap the data reader into a using statement so the lines would read: 通常,我会将数据读取器包装到using语句中,这样行将显示为:

using(var reader = command.ExecuteReader())
{
   dataTable.Load(reader);
}

I think that I'll schedule the time in to update these methods to include a using statement for the data reader as well, but I was wondering whether anyone knew whether, in the instance above, the datareader will get disposed of when the command or connection is disposed of anyway? 我想我会安排时间来更新这些方法,以包括数据读取器的using语句,但是我想知道是否有人知道在上面的实例中,当命令或连接被处置了吗?

You have to do it yourself, since the command doesn't clear up the DataReader for you. 您必须自己做,因为该命令不会为您清除DataReader See as an example SqlCommand.Dispose . 参见示例SqlCommand.Dispose

It is save in this situation to use a using since DataTable.Load doesn't keep a reference to the DataReader used. 由于DataTable.Load不会保留对所用DataReader的引用,因此在这种情况下可以使用using As a proof of that, see the reference source of DataTable . 作为证明,请参见DataTable参考源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM