在c#

时间:2018-12-12 20:24:18

标签: c# .net retry-logic

我试图创建一个重试逻辑,该逻辑有一个时间限制,可以说是6秒,重试计数为6次(包括第一次尝试),如果重试在1秒之前失败,则它将在第二秒的其余时间内休眠然后仅在下一秒内尝试该请求。除了以下一种方法,我不知道是否有一种更好的方法来实现。

我尝试的是

  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;
    }

非常感谢您的帮助,

0 个答案:

没有答案