How to reuse code that reopens connection?

后端 未结 4 1716
旧时难觅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条回答
  •  天涯浪人
    2020-12-22 01:00

    There's a few things I'm not loving in the code sample. But, to explicitly answer your question on removing duplication - extract out the common code to a method that takes a delegate.

    private TReturn RestoreConnectionAndExecute(SqlCommand command, Func execute) 
    {
       int retryCount = 0;
       while (retryCount++ < MaxRetryCount)
       {
           try
           {
              if (command.Connection.State == ConnectionState.Close) 
                  command.Connection.Open();
              return execute(command);
           } 
           catch(Exception e)
           {
              ...
       }
    }
    
    public SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command) 
    {
       return this.RestoreConnectionAndExecute(command, c => c.ExecuteReader());
    }
    
    public void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
    {
       // Ignore return
       this.RestoreConnectionAndExecute(command, c => c.ExecuteNonQuery());
    }
    

    You should really rethink a few things, though. Including:

    • Catching specific exceptions
    • Using Exception.Number or ErrorCode instead of the message (which will change in localized versions, and possibly in updated FX versions)
    • Using statements for IDisposable resources
    • Throwing specific exceptions

提交回复
热议问题