views:

164

answers:

2

I have a C# database layer that with static read method that is called every second in background timer.

currently I create SqlCommand, SqlConnection once as a class memeber.

In every method call I execute the command to get the results,I am doing so to avoid creation of connection and command every second, but I am afraid from exception occurs in this method that will break the connection or put the object in the invalid state.

This is my current implementation (Timer Handler)

    static void GetBarTime(object state)
    {
        lock (_staticConnection)
        {
            SqlDataReader dataReader = null;
            try
            {
                dataReader = _getMaxTimeCommand.ExecuteReader();
                dataReader.Read();
                _currentTick = dataReader.GetInt32(0);
            }
            catch (Exception ex)
            {
                //Log the error
            }
            finally
            {
                dataReader.Dispose();
            }
        }
    }

What is the best practise?

MORE DETAILS:

I am doing this in a timer as there is another prorcess update my table every second, and there is another exposed method used by set of clients and called every second to get the latest value.

So instead of executing select statement every second for each client, I am doing it in a timer and update global variable that is used by the clients.

+1  A: 

It can be pretty difficult to find out if an execption means that the connection is a dead duck. To be on the safe side, you could close and reopen the SqlConnection and SqlCommand whenever you encounter an exception, just in case. That doesn't cause any overhead when everything works alright.

ammoQ
So I can use the same code but just in the exception handling just close and open the connection again?
Ahmed Said
IMO better: In the exception handler, just close it and set it to null. In GetBarTime, in the lock() block, check if the connection is null; if it is, open it and create the SqlStatement. By doing it this way, it's easier to avoid problems when the database is unavailable for some time.
ammoQ
(continued) because if something caused an exception, re-opening the connection might fail as well...
ammoQ
+2  A: 

SqlConnection has pooling built in; you would see almost no difference if you used:

using(SqlConnection conn = new SqlConnection(connectionString)) {
    conn.Open();
    // your code
}

each time. And that can react automatically to dead (underlying) connections.

Currently you have a bug, btw; if the command fails, the reader will still be null... either check for null before calling Dispose():

if(dataReader !=null) {dataReader.Dispose();}

or just use using:

 try
 {
     using(SqlDataReader dataReader = _getMaxTimeCommand.ExecuteReader())
     {
         dataReader.Read();
         _currentTick = dataReader.GetInt32(0);
     }
 }
 catch (Exception ex)
 {
    //Log the error
 }
Marc Gravell
Good, but for the logic, is it better or create connection and command for each call?
Ahmed Said
Usually yes, it is better per call; you have no issues with state management / threading / etc. It also depends in part on what the command looks like - a stored procedure won't have any real advantage in keeping a prepared command around, for example.
Marc Gravell
I am not asking for the general case, for my case the method called every second, I know there is connection pool but opening and closing connection every call will consume some time comparing to have dedicated connection for this mehod
Ahmed Said
No, not really - the underlying connection remains open. You only have the time to fetch from the managed pool, which is absolutely tiny, and you'll *never* be able to measure this compared to the time to do out-of-processs (and probably network-based) IO to the server.
Marc Gravell