FelipeFonsecabh
FelipeFonsecabh

Reputation: 187

Problem with connection timeout SQL Server

I'm developing a Windows service in C# that collects data from SQL Server in another machine on the local network.

However, it is necessary to deal with if this other machine is not available, and as it is a local network, the timeout for opening the connection can be very small (10 seconds).

I defined connection timeout in the connection string, but it is not working. I try the "Connect Timeout" property too.

When the code executes sqlconn.Open without the other machine in the network being active, it's taking almost two minutes to return the timeout, and I set it to 10 seconds.

I read some cases on the site that encourage creating your own timeout mechanism using async/await, but I don't think I can use that in my code, any ideas what I can do?

Here's my code:

        public struct E3Data
        {
            public DateTime dt;
            public float value;
        }
        
        public E3Data GetSQLData()
        {
            E3Data e3 = new E3Data()
            string queryString = "SELECT TOP 1 DATEADD(HOUR,DATEDIFF(HOUR,CAST(E3TimeStamp AS DATE),E3TimeStamp),CAST(CAST(E3TimeStamp AS DATE) AS DATETIME)) As DateFormatted, [Nível Montante TDA (m)] AS Nivel FROM " + strtable+"_SASE ORDER BY E3TimeStamp DESC";
            string connectionString = "Server=192.168.80.4;Database=COR;User Id=user;Password=pass;Connect Timeout=5";
            
            using (SqlConnection sqlconn = new SqlConnection(connectionString))
            {
                SqlCommand sqlcmd = new SqlCommand(queryString, sqlconn);
                
                try
                {
                    sqlconn.Open(); //here's the problem. In case other machine not available, the timeout must act within 5 seconds
                    SqlDataReader reader = sqlcmd.ExecuteReader();
                    reader.read();
                    e3.Value = reader["Level"]
                    e3.dt = reader["dateF"]
                    
                    reader.Close()
                }
                catch
                {
                    log("DB Open error");
                }
                return e3;
            }

Upvotes: 0

Views: 65

Answers (0)

Related Questions