Polly C# Tutorial
Polly is an open-source .Net library used to handle retry logic in your application. There may be cases when you might want to retry a service call if it fails due to transient errors. Transient errors include errors like Server currently busy, database not available, Not enough resource to process requests etc.
Polly provides a callback mechanism where you can retry and configure the number of retries that you want to perform until you record the failure.
How to install Polly Nuget package-
1. dotnet CLI Command - dotnet add package Polly
2. Install the nuget package from Visual Studio - Search for Polly in 'Manage nuget packages'
Retry Call without using Polly - The below implementation does not look pretty to read as it obscures the actual logic to call the service.
private void CallExternalService()
{
const int RETRY_ATTEMPTS = 3;
for (int i =0, i<RETRY_ATTEMPTS,i++)
{
Thread.Sleep(i * 100);
CallExternalService();
//If Call Success => exit the lopp
break;
}
catch(Exception)
{
Log(exception);
}
}
Examples
Retry Forever - The service is called again and again until it succeeds
Policy.Handle<Exception>()
.RetryForever()
.Execute(CallExternalService);
Handle only certain exceptions -
Policy.Handle<IOException>().Or<UnauthorizedAccessException>()
.RetryForever()
.Execute(CallExternalService);
Log the error message during retries -
Policy.Handle<IOException>().Or<UnauthorizedAccessException>()
.RetryForever(ex => Log(ex))
.Execute(CallExternalService);
Retry n Times
Policy.Handle<Exception>()
.Retry(10)
.Execute(CallExternalService);
Log the error message during retries
Policy.Handle<Exception>()
.Retry(10, (e, i) => Log($"Error '{e.Message}' at retry #{i}"))
.Execute(CallExternalService);
WaitandRetry
You can specify the timespan collection stating how long you need to wait before each retry. The retry attempts are based on how many items are present in the collection.
Policy.Handle<Exception>()
.WaitAndRetry(new []
.{ TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(200) }) .Execute(CallExternalService);
Calculate wait times dynamically -
Policy.Handle<Exception>()
.WaitAndRetry(5, count => TimeSpan.FromSeconds(count))
.Execute(CallExternalService);
Calculate wait times dynamically and an infinite number of retries -
Policy.Handle<Exception>()
.WaitAndRetry(count => TimeSpan.FromSeconds(count))
.Execute(CallExternalService);
Real-world Example -
var httpTask = Policy
. HandleResult<(TMessageReturned m, int s)>(t => t.m == null && serviceRetryConfig.StatusCodesToRetry.Contains(t.s))
.WaitAndRetryAsync(serviceRetryConfig.MaxRetry,
i => TimeSpan.FromMilliseconds(serviceRetryConfig.SlidingIntervalInMs),
onRetry: (result, timespan, retrycount,context) =>
{
count++;
})
.ExecuteAsync(() => CallExternalService<TMessageSent, TMessageReturned>(messagebody));
Comments
Post a Comment