Is there a difference in declaring an IDisposable member to use a block or when using a block declaration?

I have the code below:

    using (SqlCommand command = new SqlCommand())
    {

        command.CommandType = System.Data.CommandType.StoredProcedure;
        command.Connection = new SqlConnection();
        command.CommandText = "";

        command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input);

        SqlDataReader dataReader = command.ExecuteReader();
   }

Is there any functional impact when declaring SqlConnection, where am I currently declaring it, and not like that ?:

using (SqlCommand command = new SqlCommand())
using (SqlConnection connection = new SqlConnection())

thank

+3
source share
4 answers

Yes, there is a difference. Disposal SqlCommandis not automatically associated SqlConnectionwith which it is associated. You can proceed this way, and this will interfere with the union of ADO.NET connections; if you look at the activity of the database server during the execution of this code, you will see new connections that will be open and will not be closed.

. , SqlConnection - , Dispose. , IDisposable , SqlConnection.

+5

, 2, , 1 .

1, , .

. IDispsoable, using() { }, .

+3

:

using(var connection = new SqlConnection("ConnectionName"))
using(var command = new SqlCommand())
{
   command.Connection = connection;
   // setup command
   var reader = command.ExecuteReader();
   // read from the reader
   reader.Close();
}
+2

, SqlConnection, . using ( try... finally) , , .

0

Source: https://habr.com/ru/post/1738411/


All Articles