比如网络访问或硬件参数设置需要重试,可引用gunet上的Polly库。
同步方式(每次重试有不同的时间间隔)
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}");
});
异步方式(每次重试有不同的时间间隔)
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}");
});
});
详细介绍参考:xC#调用Polly库实现捕捉异常处理的操作代码_C#教程_脚本之家Polly 是一个 .NET 弹性和瞬态故障处理库,允许开发人员以 Fluent 和线程安全的方式来实现重试、断路、超时、隔离和回退策略,本文给大家介绍了C#调用Polly库实现捕捉异常处理操作,文中有详细的代码示例供大家参考,需要的朋友可以参考下https://www.jb51.net/program/3264462an.htm
Timeout (异步,token方式,业务层需要while循环判断,不是太香)
var asyncPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(2));
await asyncPolicy.ExecuteAsync(
async ct =>
{
await Task.Run(() =>
{
while (true)
{
if (ct.IsCancellationRequested)
{
Console.WriteLine($"检测到超时,退出 ManagedThreadId={Thread.CurrentThread.ManagedThreadId}");
return;
}
Thread.Sleep(1000);
}
}).ConfigureAwait(false);
},
CancellationToken.None);