How to reuse code that reopens connection?

后端 未结 4 1727
旧时难觅i
旧时难觅i 2020-12-22 00:36

Our production server kills inactive connections, so our API needs to restore them when they are needed. The following code works, but it is very repetitive:



        
4条回答
  •  萌比男神i
    2020-12-22 01:07

    private const int MaxRetryCount = 3;
    
            public static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
            {
                return RestoreConnectionAndExecuteQueryHelper(command, true);
            }
    
            public static void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
            {
                RestoreConnectionAndExecuteQueryHelper(command, false);
            }
    
            private static SqlDataReader RestoreConnectionAndExecuteQueryHelper(SqlCommand command, bool returnReader)
            {
                var retryCount = 0;
                while (retryCount++ < MaxRetryCount)
                {
                    try
                    {
                        if (command.Connection.State == ConnectionState.Closed)
                            command.Connection.Open();
                        if (returnReader)
                        {
                            return command.ExecuteReader();
                        }
                        else
                        {
                            command.ExecuteNonQuery();
                            return null;
                        }
                    }
                    catch (Exception e)
                    {
                        if (!e.Message.ToLower().Contains("transport-level error has occurred"))
                        {
                            throw;
                        }
                    }
                }
                throw new Exception("Failed to restore connection for command:" + command.CommandText);
            }
    

提交回复
热议问题