makerofthings7
makerofthings7

Reputation: 61473

How should I handle backoff or "Wait and Retry" logic in a C# application when an exception occurs?

I am reading from a REST service and need to handle "Wait and retry" for a heavily used service that will give me an error:

Too many queries per second

or

Server Busy

Generally speaking, since I have many REST services to call, how can I generically handle backoff logic that would occur when an exception occurs?

Is there any framework that has this built in? I'm just looking to write clean code that doesn't worry too much about plumbing and infrastructure.

Upvotes: 6

Views: 1338

Answers (3)

Stephen Cleary
Stephen Cleary

Reputation: 456987

I recommend you look into the Transient Fault Handling Application Block, part of the Enterprise Library.

In the past, the EL has IMO been over-engineered and not that useful, but they've taken steps to address that; the TFHAB is one of the newer blocks that follows better design guidelines (again, IMO).

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564691

You can wrap the attempt up within a method that handles the retry logic for you. For example, if you're using WebClient's async methods:

public async Task<T> RetryQuery<T>(Func<Task<T>> operation, int numberOfAttempts, int msecsBetweenRetries = 500)
{
     while (numberOfAttempts > 0)
     {
          try
          {
               T value = await operation();
               return value;
          }
          catch
          {
                // Failed case - retry
                --numberOfAttempts;                   
          }

          await Task.Delay(msecsBetweenRetries);
     }

     throw new ApplicationException("Operation failed repeatedly");
}

You could then use this via:

// Try 3 times with 500 ms wait times in between
string result = await RetryQuery(async () => webClient.DownloadStringTaskAsync(url), 3);

Upvotes: 5

Codeman
Codeman

Reputation: 12375

Try and determine how many active requests can be active at a time and use a Semaphore.

It is a way to handle resource locking where the are multiple identical resources, but only a limited number of them.

Here's the MSDN documentation on semaphores

Upvotes: 3

Related Questions