0

I tried to create a retry logic that has a time limit lets say 6 seconds with a retry count of 6 times (including the first try) and if a retry is failed before 1sec , it will sleep for the rest of the second and try the request in the next second only . I don't know if there is a better way to achieve this other than the one below .

What I tried is

  public bool RetryFunc(Func<Response,bool> function, DataModel data)
    {
        int duration=6; //in seconds
        int retryCount=5; 
        bool success = false;
        Stopwatch totalRetryDurationWatch = new Stopwatch();// begin request
        totalRetryDurationWatch.Start();// first try
        success = function(data);
        int count = 1;
        while (!success && count <= retryCount)
        {
            Stopwatch thisRetryDurationWatch = new Stopwatch();// Begining of this retry
            thisRetryDurationWatch.Start();
            success = function(data);//End this retry
            thisRetryDurationWatch.Stop();
            if (totalRetryDurationWatch.Elapsed.Seconds>=duration)
            {
                return false;
            }
            else if (!success) {
   // To wait for the second to complete before starting another retry
                if (thisRetryDurationWatch.ElapsedMilliseconds < 1000) 
                    System.Threading.Thread.Sleep((int)(1000 - thisRetryDurationWatch.ElapsedMilliseconds));
            }
            count++;
        }
        totalRetryDurationWatch.Stop();//To end the retry time duration watch
        return success;
    }

Any help is much appreciated , Thanks .

Sachin
  • 2,627
  • 1
  • 19
  • 35
  • 2
    How about [Polly](https://github.com/App-vNext/Polly) – JSteward Dec 12 '18 at 20:28
  • @npo , its not a duplicate , those didn't check for duration of the overall retry . – Sachin Dec 12 '18 at 20:31
  • @JSteward I was checking if there is a better way other than using 3rdparty plugins , thanks. – Sachin Dec 12 '18 at 20:36
  • This seems like it'll do what you want just fine, it could perhaps be tidied up a bit by removing the first try at the top and initialising your counter to 0, so your first try is including in the while loop. I think you could also just use DateTime.Now() to get the current time and store it in a variable and do the same later to get the elapsed time. I'm not sure if their's any pros/cons with using Stopwatch? On more of an implementation note, most libraries I've encountered will throw System.TimeoutException when a desired function can't be completed within a specified timeout. – TheBeardedQuack Dec 12 '18 at 20:51

0 Answers0