比如网络访问或硬件参数设置需要重试,可引用gunet上的Polly库。
同步方式(每次重试有不同的时间间隔)
cs
var polly = Policy.Handle<Exception>().WaitAndRetry(new[] { new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 3) }, (ex, t, retryCnt, context) => {
Debug.WriteLine($"{ex.Message}, {t}, {retryCnt}");
});
polly.ExecuteAndCapture(() => {
Thread.Sleep(1000);
var random = new Random();
var v = random.Next(0, 10);
if (v < 50)
throw new Exception("V < 50");
Debug.WriteLine($"polly.ExecuteAndCapture {Thread.CurrentThread.ManagedThreadId}");
});
异步方式(每次重试有不同的时间间隔)
cs
var polly = Policy.Handle<Exception>().WaitAndRetryAsync(new[] { new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 10) }, (ex, t, retryCnt, context) => {
Debug.WriteLine($"{ex.Message}, {t}, {retryCnt} ThreadID={Thread.CurrentThread.ManagedThreadId}");
});
polly.ExecuteAndCaptureAsync(async () => {
await Task.Run(() => {
Thread.Sleep(1000);
var random = new Random();
var v = random.Next(0, 10);
if (v < 50)
throw new Exception("V < 50");
Debug.WriteLine($"polly.ExecuteAndCapture {Thread.CurrentThread.ManagedThreadId}");
});
});