Using statement question

后端 未结 6 1042
挽巷
挽巷 2021-01-13 04:03

I have two questions.

1) Should you always use a using statement on a connection? So, I would use it on the connection and then another one on a reader within the c

6条回答
  •  梦谈多话
    2021-01-13 05:05

    1) Should you always use a using statement on a connection? So, I would use it on the connection and then another one on a reader within the connection? So I would be using two using statements.

    Yes, because they implement IDisposable. And don't forget a using statement on the command too :

    using (DbConnection connection = GetConnection())
    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "SELECT FOO, BAR FROM BAZ";
        connection.Open();
        using (DbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                ....
            }
        }
    }
    

    2) Lets say you use the using statement on the connection and also a reader being returned on the connection. So you have two using statements. Does it create two Try{}Finally{} blocks or just one?

    Each using statement will create its own try/finally block

提交回复
热议问题