我在这里使用的是遗留代码,SqlDataReader的许多实例从未关闭或处理过.连接已关闭,但我不确定是否需要手动管理读卡器.

这会导致性能下降吗?

推荐答案

尽量避免使用这样的阅读器:

SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
      while (reader.Read())
      {
              //do something
      }
}
reader.Close(); // <- too easy to forget
reader.Dispose(); // <- too easy to forget
connection.Close(); // <- too easy to forget

相反,请使用以下语句将它们包装起来:

using(SqlConnection connection = new SqlConnection("connection string"))
{

    connection.Open();

    using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader != null)
            {
                while (reader.Read())
                {
                    //do something
                }
            }
        } // reader closed and disposed up here

    } // command disposed here

} //connection closed and disposed here

using语句将确保正确处理对象并释放资源.

如果你忘记了,那么你将把清理工作交给垃圾收集器,这可能需要一段时间.

Sql相关问答推荐

调用存储过程时SQL服务器TDS协议响应问题

如何查询一个名称是根据PL/pgSQL函数结果构建的表?

如何从上一个值减go 值

用相同值更新行

如何连接第二个表并将其内容输入到第一个表的单个字段中?

在postgres中动态计算出现次数并插入到json中

Access 365将文本转换回BigInt

使用多个嵌套数组查询JSON数据

如何使用不重复的单个顶级字段(列)向json数组 Select 多行

SQL到Snowflake-转换嵌套的SELECT(值

如何简化此PostgreSQL查询以计算平均值?

Postgresql - WHERE 中的 MAX 标准 - 初学者问题

除了风格之外,还有什么理由更喜欢简单的CASE WHEN而不是搜索呢?

什么是 100.它与 100 有什么区别?

基于字符串的SQL查询

PostgreSQL分割字符串为子词并判断其是否存在于其他字符串中

BigQuery Pivot 遗漏行

Select 给定类别列表(或更多类别)中的所有事物

将单行中的多个行值转换为列

SQL中所有先前日期的累计总和