C# using then exception / Open Database

Markus Freitag 3,791 Reputation points
2021-02-12T12:39:21.573+00:00

Hello,

    using (SqlConnection con = new SqlConnection(strConnectionString))
    {
     foreach (var position in ListTraceData.AllPositions)
     {
         try {
                z= position.SomethingToDo;
         }
         catch (Exception ex)
         {
            WriteLog("Error writing to database: " + ex.Message);
            throw new MyException("Error from OPC", Hm.Null, ex);
         }        
     }        
    }

If an exception occurs within the using statement, will it still close correctly?

Is it better to leave a database always open or better to open it when necessary?

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2021-02-12T15:09:07.263+00:00

    "If an exception occurs within the using statement, will it still close correctly?"

    Yes that is the entire point of the using statement. It is guaranteed to dispose (close in the case of the db connection) the object when the statement ends whether an exception occurs or not.

    "Is it better to leave a database always open or better to open it when necessary?"

    Open the connection, use it and then close it. That is the best for performant code. Leaving a connection open wastes a dedicated connection to the DB and can limit the ability of an app to scale. It also is critical for error handling as some errors (such as network drops) will break the connection. Any attempt to reuse the connection will fail. Opening the connection each time you need it will properly recover from these errors as the runtime will detect the bad connection and create a new one. The runtime pools connections so you don't have the overhead of a database connection each time you call open.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Castorix31 90,686 Reputation points
    2021-02-12T12:58:56.383+00:00

    You can see at : SqlException Class

    "The SqlConnection remains open when the severity level is 19 or less.
    When the severity level is 20 or greater, the server ordinarily closes the SqlConnection. However, the user can reopen the connection and continue.
    In both cases, a SqlException is generated by the method executing the command.

    "

    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 122.6K Reputation points
    2021-02-12T14:27:20.947+00:00

    According to documentation, “using statement ensures that Dispose (or DisposeAsync) is called even if an exception occurs within the using block”. Therefore, con.Dispose() will be called automatically in both of normal and exceptional cases.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.