我需要明确关闭并处置SQLConnection?

问题描述 投票:0回答:3
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。因此,结束使用范围时,连接对象是否会自动处置?
    

c# asp.net ado.net dispose sqlconnection
3个回答
7
投票
SqlConnection

,因为它是一个可支配的对象。您可以尝试一下:

using(var sqlConnection = new SqlConnection(objUtilityDAL.ConnectionString))
{
    using (SqlCommand cmd = con.CreateCommand())
    {
        // the rest of your code - just replace con with sqlConnection
    }
}

我建议您用局部变量替换
con

-如果还没有替换(从您发布的代码中看不出)。无需为此目的使用类字段。只需创建一个局部变量,跟踪它就会更加清楚。

    

您应该每一个the the thuce the创建

3
投票
Dispose

请注意,请注意
IDisposable
至少是redredledenti(它什么都没有,但请重新删除异常,而放弃堆栈跟踪),这就是为什么可以删除的原因。
    
一般:
在.NET框架中,没有什么可以自动丢弃的。否则,我们将不需要
using

接口。垃圾收集器只能处理托管资源,因此必须在Dispose方法中以代码处理每个不受管理的资源。 chiss通常,必须通过调用其
   // 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; }

语句来显式处理每个实施该类别的每个类的实例。
最佳实践,您应该努力使用将
IDisposable

接口用作a内部的局部变量的任何东西: IDisposable 语句是句法糖。编译器将其翻译成这样的东西:


2
投票

从保证运行的block incance无论在

using

块中发生什么都可以运行,您的

IDisposable
实例可以正确处理。

特别是,在订单中,将连接对象返回连接池

,您必须在完成时将其处置(Dispose方法也将关闭连接,因此您无需明确关闭它) - 因此,正确使用的正确使用

using(var whatever = new SomeIDisposableImplementation())
{
    // use the whatever variable here
}
using
always
作为local variable作为local varible语句:

var whatever = new SomeIDisposableImplementation(); try { // use the whatever variable here } finally { ((IDisposable)whatever).Dispose(); }

语句:

finally

try
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.