Created
November 4, 2017 06:19
-
-
Save wanghuaisheng/ea01ee9302e1078346d902d9f1921c10 to your computer and use it in GitHub Desktop.
保证action方法成功执行一次
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// 保证action方法成功执行一次 | |
/// </summary> | |
/// <param name="action"></param> | |
/// <param name="timeOut">在指定时间内执行</param> | |
/// <exception cref="TimeoutException">在指定时间内未能成功执行完,则抛出异常</exception> | |
public static void RetryUntilTrue(Func<bool> action, TimeSpan? timeOut = null) | |
{ | |
var num = 0; | |
var now = DateTime.Now; | |
while (!timeOut.HasValue || DateTime.Now - now < timeOut.Value) | |
{ | |
num++; | |
if (action()) | |
{ | |
return; | |
} | |
SleepBackOffMultiplier(num); | |
} | |
throw new TimeoutException($"Exceeded timeout of {timeOut.Value}"); | |
} | |
/// <summary> | |
/// 阻塞此方法调用体,阻塞随机毫秒数(i的2次方至i+1的2次方区间) | |
/// </summary> | |
/// <param name="i"></param> | |
private static void SleepBackOffMultiplier(int i) | |
{ | |
var random = new Random(Guid.NewGuid().GetHashCode()); | |
var millisecondsTimeout = random.Next((int)Math.Pow(i, 2.0), (int)Math.Pow(i + 1, 2.0) + 1); | |
Thread.Sleep(millisecondsTimeout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment