(一)Policy知识体系图
(二)代码案例分析
(1)Retry()函数
public static int TestRetry() { int b = 0; var policy = Policy.Handle<DivideByZeroException>().Retry(3, (ex, i) => { Console.WriteLine($"Retry:{i} 异常信息:{ex.Message}"); }); try { policy.Execute(() => { int a = 10; b = a / 0; }); } catch (Exception ex) { Console.WriteLine($"异常:{ex.Message}"); } return b; }
public static int TestTimout() { var policy = Policy.Handle<Exception>().Fallback(() => { Console.WriteLine("Fallback"); }).Wrap(Policy.Handle<Exception>().Retry(3, (ex, i) => { Console.WriteLine($"Retry {i}"); })) .Wrap(Policy.Timeout(3, (context, ts, task) => { Console.WriteLine("Timeout"); })); var cts = new CancellationTokenSource(); policy.Execute(ct => { for (int i = 0; i < 1000; i++) { Console.WriteLine($"Execute:{i}"); Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); } }, cts.Token); return 0; }