Polly is one. NET elastic and transient fault handling libraries that allow developers to express policies such as retries, circuit breakers, timeouts, quarantine headers, and fallbacks in a smooth and thread-safe manner.

Polly. NET Standard 1.1 (coverage:.NET Core 1.0, Mono, Xamarin, UWP, WP8.1 +) and NET Standard 2.0+ (coverage:.NET Core 2.0+,.NET Core 3.0, and later Mono, Xamarin, and UWP targets). The Nuget package also includes. NET Framework 4.6.1 and 4.7.2.

use

Install via NuGet

Install-Package Polly
Copy the code

usage

Fault handling and response policies

Troubleshooting policies handle specific exceptions or returned results that are raised by delegates that you execute through policies.

Step 1: Specify the exception/error that you want the policy to handle

// Single exception type Policy .Handle<HttpRequestException>() // Single exception type with condition Policy .Handle<SqlException>(ex => ex.Number == 1205) // Multiple exception types Policy .Handle<HttpRequestException>() .Or<OperationCanceledException>() // Multiple exception types with condition Policy .Handle<SqlException>(ex => ex.Number == 1205) .Or<ArgumentException>(ex => ex.ParamName == "example") // Inner exceptions of ordinary exceptions or  AggregateException, with or without conditions // (HandleInner matches exceptions at both the top-level and inner exceptions) Policy .HandleInner<HttpRequestException>() .OrInner<OperationCanceledException>(ex => ex.CancellationToken ! = myToken)Copy the code

Step 2: Specify how the policy should handle these failures

2.1 try again,

// Retry once
Policy
  .Handle<SomeExceptionType>()
  .Retry()

// Retry multiple times
Policy
  .Handle<SomeExceptionType>()
  .Retry(3)

// Retry multiple times, calling an action on each retry 
// with the current exception and retry count
Policy
    .Handle<SomeExceptionType>()
    .Retry(3, onRetry: (exception, retryCount) =>
    {
        // Add logic to be executed before each retry, such as logging
    });

// Retry multiple times, calling an action on each retry 
// with the current exception, retry count and context 
// provided to Execute()
Policy
    .Handle<SomeExceptionType>()
    .Retry(3, onRetry: (exception, retryCount, context) =>
    {
        // Add logic to be executed before each retry, such as logging 
    });
Copy the code

2.2. Always retry (until Successful)

// Retry forever Policy .Handle<SomeExceptionType>() .RetryForever() // Retry forever, calling an action on each retry with the // current exception Policy .Handle<SomeExceptionType>() .RetryForever(onRetry:  exception => { // Add logic to be executed before each retry, such as logging }); // Retry forever, calling an action on each retry with the // current exception and context provided to Execute() Policy .Handle<SomeExceptionType>() .RetryForever(onRetry: (exception, context) => { // Add logic to be executed before each retry, such as logging });Copy the code

2.3. Wait and try again

// Retry, waiting a specified duration between each retry. 
// (The wait is imposed on catching the failure, before making the next try.)
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(new[]
  {
    TimeSpan.FromSeconds(1),
    TimeSpan.FromSeconds(2),
    TimeSpan.FromSeconds(3)
  });

// Retry, waiting a specified duration between each retry, 
// calling an action on each retry with the current exception
// and duration
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(new[]
  {
    TimeSpan.FromSeconds(1),
    TimeSpan.FromSeconds(2),
    TimeSpan.FromSeconds(3)
  }, (exception, timeSpan) => {
    // Add logic to be executed before each retry, such as logging    
  }); 

// Retry, waiting a specified duration between each retry, 
// calling an action on each retry with the current exception, 
// duration and context provided to Execute()
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(new[]
  {
    TimeSpan.FromSeconds(1),
    TimeSpan.FromSeconds(2),
    TimeSpan.FromSeconds(3)
  }, (exception, timeSpan, context) => {
    // Add logic to be executed before each retry, such as logging    
  });

// Retry, waiting a specified duration between each retry, 
// calling an action on each retry with the current exception, 
// duration, retry count, and context provided to Execute()
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(new[]
  {
    TimeSpan.FromSeconds(1),
    TimeSpan.FromSeconds(2),
    TimeSpan.FromSeconds(3)
  }, (exception, timeSpan, retryCount, context) => {
    // Add logic to be executed before each retry, such as logging    
  });

// Retry a specified number of times, using a function to 
// calculate the duration to wait between retries based on 
// the current retry attempt (allows for exponential backoff)
// In this case will wait for
//  2 ^ 1 = 2 seconds then
//  2 ^ 2 = 4 seconds then
//  2 ^ 3 = 8 seconds then
//  2 ^ 4 = 16 seconds then
//  2 ^ 5 = 32 seconds
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(5, retryAttempt => 
  TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) 
  );

// Retry a specified number of times, using a function to 
// calculate the duration to wait between retries based on 
// the current retry attempt, calling an action on each retry 
// with the current exception, duration and context provided 
// to Execute()
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(
    5, 
    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, context) => {
      // Add logic to be executed before each retry, such as logging
    }
  );

// Retry a specified number of times, using a function to 
// calculate the duration to wait between retries based on 
// the current retry attempt, calling an action on each retry 
// with the current exception, duration, retry count, and context 
// provided to Execute()
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(
    5, 
    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) => {
      // Add logic to be executed before each retry, such as logging
    }
  );
Copy the code

Open source address:

Github.com/App-vNext/P…