Cleanest way to write retry logic?

前端 未结 29 2572
旧巷少年郎
旧巷少年郎 2020-11-22 03:01

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
         


        
29条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 03:22

    You should try Polly. It's a .NET library written by me that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

    Example

    Policy
        .Handle(ex => ex.Number == 1205)
        .Or(ex => ex.ParamName == "example")
        .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(3))
        .Execute(() => DoSomething());
    

提交回复
热议问题