HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpModerate

Attempt to reconnect, with timeout

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withtimeoutreconnectattempt

Problem

I have a situation in which a program, communicating over the network, can timeout or otherwise fail to establish a connection through no fault of my application or its user. If and when this happens, an exception is thrown. The solution is obvious; simply try again a couple more times, and if multiple tries don't work then this is really a problem.

I've accomplished this by wrapping the original try-catch in a while loop with a retry counter, producing the following basic pattern:

var retryCount = 0;
while(true)
{
   try
   {
      AttemptToConnect();
      break;
   }
   catch(TimeoutException tex)
   {
      if(++retryCount < 3) continue;

      throw; //or handle error and break/return
   }
}


Do any of you see any problems? The biggest smell, prompting me to ask in the first place, is the conditionless loop, which would be infinite except that the "happy path" breaks out of the loop manually, while the terminating error will throw out. This has been called out before as a potential bug generator, if it's ever modified in the future (for instance to catch a second type of exception, or to do something else that could throw an exception).

Solution

Yeah, I'd probably redo it with an actual condition. That way, intent looks clear and is not dependent on internal code to break, continue, etc.

const int NumberOfRetries = 3;
var retryCount = NumberOfRetries;
var success = false;
while(!success && retryCount > 0)
{
   try
   {
      AttemptToConnect();
      success = true;
   }
   catch(TimeoutException tex)
   {
      retryCount--;

      if (retryCount == 0)
      {
          throw; //or handle error and break/return
      }
   }
}

Code Snippets

const int NumberOfRetries = 3;
var retryCount = NumberOfRetries;
var success = false;
while(!success && retryCount > 0)
{
   try
   {
      AttemptToConnect();
      success = true;
   }
   catch(TimeoutException tex)
   {
      retryCount--;

      if (retryCount == 0)
      {
          throw; //or handle error and break/return
      }
   }
}

Context

StackExchange Code Review Q#31059, answer score: 12

Revisions (0)

No revisions yet.