Using Use to Recycle Nested Objects

If I have code with nested objects like this, I need to use nested using statements to make sure that the SQLCommand and SQLConnection objects are deleted correctly, as shown below, or I'm fine if the code that creates the SQLCommand instance is inside an external statement using.

using (var conn = new SqlConnection(sqlConnString))
{
    using (var cmd = new SqlCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = cmdTextHere;
        conn.Open();

        cmd.Connection = conn;
        rowsAffected = cmd.ExecuteNonQuery();
    }
}
+5
source share
4 answers

Yes. You can clean it a little.

using (SqlConnection conn = new SqlConnection(sqlConnString))
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
   // code here
}

But you still want usingan IDisposable for each object.

Edit: Consider an example of using an internal operator using.

class A : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("A Disposed");
    }
}

class B : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("B Disposed");
    }
}

the code

using (A a = new A())            
{
    B b = new B();
}

. B? , . B.Dispose() . ,

using (A a = new A())
using (B b = new B())
{
}

(, ), Dispose() .

+8

dispose , , :

using (SqlConnection conn = new SqlConnection(sqlConnString)) 
using (SqlCommand cmd = new SqlCommand()) 
{ 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = cmdTextHere; 
     conn.Open(); 

     cmd.Connection = conn; 
     rowsAffected = cmd.ExecuteNonQuery(); 
} 

, (, if ), , , . , , , , .

+4

SqlCommand. GC . . , .

SqlCommand System.ComponentModel.Component, Finalizer. dispose SqlCommand , ( .NET - ). : 1, 2. , , . , , , . , , SqlConnection, SqlParameter, CommandText , . , , , .

, .

.NET , CLR . . , , , ( , ), , CLR . OutOfMemoryException.

, , , SqlCommand. , OOM , .

, , GC (finalizable). . Reflector , , , ( ).

+4

, , .

Since the object is SqlCommandlimited by external curly braces, it will be assembled by the GC when execution exits the block.

Other answers are also in order, but they certainly did not answer your question :)

0
source

All Articles