Alright, here's my opinion:

The "Using" construct is functionally equivalent to a Try-Finally
construct. It is a developer convenience and the compiler will convert
the former to the latter. So, there is no difference in performance in
the two. However, the Try-Finally construct does not provide for a
structured way to handle exceptions (it omits the Catch block and all
exceptions are bubbled up to the calling code. This is the point you
need to consider... Does your code require all exceptions to be
handled here itself ? If so, you will have to refactor into Try-Catch-
Finally constructs. If not, you're good with using Using ! (pun
intended)

The code you presented is very well formed. It is hard to be more
efficient except for a single point that I noticed - You open the
Connection early on. For highest performance, you should open your
Connection as late as possible and dispose of it as soon as possible.

IOW, the Connection.Open() call should be just before the
SqlDataReader is created.

On May 27, 3:01 pm, Chris Marks <[email protected]> wrote:
> I've posted this on a couple forums, but in order to gain a wider
> audience, and possible responses I thought i'd post it here too!
>
> I normally connect to a database as follows:
>
> using (SqlConnection connection = new SqlConnection
> ("connectionString"))
> {
>   connection.Open();
>   using (SqlCommand command = new SqlComamnd
> ("storedProc",connection))
>   {
>     command.CommandType = CommandType.StoredProcedure;
>     command.Parameters.AddWithValue("@P1",Value);
>     using (SqlDataReader reader = command.ExecuteReader())
>     {
>       if (reader.HasRows)
>       {
>         reader.Read();
>         // rest of code to populate tables, etc here
>       }
>     }
>   }
>
> }
>
> However, shortly I'm going from typically serving say 200 users, to
> more like 60,000 users, and as such I'd like to ensure that I'm doing
> everything I can to create efficient code.  I've been looking at other
> examples, using the "try/catch/finally" methods, but further reading
> supports using "using" more so, due to the fact that it will always
> clean up.
>
> With regard to trapping errors in the commands/connections - should I
> be using a try/catch/finally block within my "using" blocks?
>
> TIA!
>
> Chris
>
> Thanks!

Reply via email to