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:
private const int MaxRetryCount = 3;
public static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
{
int retryCount = 0;
while (retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
return command.ExecuteReader();
}
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);
}
public static void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
{
var retryCount = 0;
while(retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
command.ExecuteNonQuery();
return;
}
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);
}
How could I refactor my code and eliminate duplication? I need to keep the signatures of these methods, as they are used all over the system.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…