我是否需要关闭并显式处置SQLConnection? [英] Do I need to close and dispose the SQLConnection explicitly?

查看:77
本文介绍了我是否需要关闭并显式处置SQLConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlDataReader rdr = null;
con = new SqlConnection(objUtilityDAL.ConnectionString);
using (SqlCommand cmd = con.CreateCommand())
{
    try
    {
        if (con.State != ConnectionState.Open)
            con.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(Parameter);
        cmd.CommandText = _query;
        rdr = cmd.ExecuteReader();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

在上面的代码中,sqlconnection在托管代码内打开.因此,在结束USING范围时,连接对象会自动处置吗?

In this above code, sqlconnection is opened inside the managed code. Hence, will the connection object be disposed automatically upon ending the scope of USING?

推荐答案

创建的每个临时 IDisposable 实例,应处置手动,即使用将它们包装到:

You should Dispose every temporary IDisposable instance you create manually, i.e. wrap them into using:

   // Connecton is IDisposable; we create it 
   //   1. manually - new ...
   //   2. for temporary usage (just for the query)
   using (SqlConnection con = new SqlConnection(objUtilityDAL.ConnectionString)) {
     // Check is redundant here: new instance will be closed 
     con.Open();

     // Command is IDisposable
     using (SqlCommand cmd = con.CreateCommand()) {
       cmd.CommandType = CommandType.StoredProcedure;
       cmd.Parameters.Add(Parameter);
       cmd.CommandText = _query;

       // Finally, Reader - yes - is IDisposable 
       using (SqlDataReader rdr = cmd.ExecuteReader()) {
         // while (rdr.Read()) {...}
       }
     }   
   }

请注意

   try {
     ...
   }
   catch (Exception ex) {
     throw ex;
  } 

至少是冗余(它没有任何作用,只是抛出了异常,同时失去了堆栈跟踪),这就是为什么可以将其丢弃

is at least redundant (it does nothing but rethrow the exception, while loosing stack trace) and that's why can be dropped out

这篇关于我是否需要关闭并显式处置SQLConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆