我试图创建一个重试逻辑,它有一个时间限制,比如说 6 秒,重试次数为 6 次(包括第一次尝试),如果在 1sec 之前重试失败,它将在剩下的第二秒内休眠并尝试只在下一秒请求。我不知道除了下面的方法之外是否有更好的方法来实现这一点。
我尝试的是
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;
}
非常感谢任何帮助,谢谢。