我是否需要明确关闭并处理SQLConnection?

Chi*_*han 2 c# asp.net ado.net 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*tos 6

你必须关心处理SqlConnection,因为它是一次性物品.你可以试试这个:

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

我建议你con用一个局部变量替换- 如果还没有(从你发布的代码中看不出来).不需要为此目的使用类字段.只需创建一个局部变量,跟踪它就会更加清晰.