【发布时间】:2013-10-30 15:07:25
【问题描述】:
我使用以下方法对数据库执行查询并读取数据:
using(SqlConnection connection = new SqlConnection("Connection string"))
{
connection.Open();
using(SqlCommand command = new SqlCommand("SELECT * FROM TableName", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
// read and process data somehow (possible source of exceptions)
} // <- reader hangs here if exception occurs
}
}
在读取和处理数据时,可能会发生一些异常。问题是当DataReader 抛出异常时,Close() 调用挂起。你有什么想法为什么???以及如何以适当的方式解决这个问题?当我写try..catch..finally 块而不是using 并调用command.Cancel() 之后,问题就消失了,然后将阅读器置于finally 中。
工作版本:
using(SqlConnection connection = new SqlConnection("Connection string"))
{
connection.Open();
using(SqlCommand command = new SqlCommand("SELECT * FROM TableName", connection))
{
SqlDataReader reader = command.ExecuteReader();
try
{
// read and process data somehow (possible source of exceptions)
}
catch(Exception ex)
{
// handle exception somehow
}
finally
{
command.Cancel(); // !!!
reader.Dispose();
}
}
}
【问题讨论】:
-
调试器之外是否也会发生这种情况?
-
using 块会自动关闭和处理!您不必在 using 块中关闭它。同时在 using 块中向我们展示您的代码
-
try/catch块中的全部内容告诉异常是什么。如果您不告诉我们异常是什么,我们将无能为力。 -
@P.Brian.Mackey 这发生在调试器之外,这就是我不得不使用调试器的原因。
-
@BlackFrog 嗯,异常不对应数据库交互,任何类型的异常。我自己抛出异常。如果发生任何异常,唯一的事实是阅读器挂起。
标签: c# .net sqldatareader