我使用以下方法来执行数据库查询和读取数据:
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
并在 finally
中释放读取器之前调用 command.Cancel()
时,问题已经解决。
工作版本:
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();
}
}
}
try/catch
告诉我们异常是什么。如果您不告诉我们异常是什么,我们就无法提供帮助。 - Black Frog