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

I am reading from a REST service and should handle "Wait and try again" for a heavily used service that will give me an error:

Too many requests per second

or

Server busy

Generally speaking, since I have many REST services to call, how can I generally handle the delay logic that would occur if an exception occurred?

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

+6
source share
3 answers

You can wrap the attempt as part of a method that handles the retry logic for you. For example, if you use WebClient 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"); } 

Then you can use this via:

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

Try to determine how many active queries can be active at a time, and use Semaphore .

This is a way to handle resource locks when they have several identical resources, but only a limited number of them.

Here's the MSDN semaphore documentation

+3
source

I recommend that you take a look at the Transient Processing Application Suite , which is part of the Enterprise Library.

In the past, EL had IMOs that were overly designed and not so useful, but they took steps to address this; TFHAB is one of the new blocks that follow the best design guidelines (again, IMO).

+3
source

Source: https://habr.com/ru/post/956027/


All Articles