Using Polly (! the parrot) in .NET

Dima Pursanov
eMoney Engineering
Published in
2 min readMay 2, 2017
the !parrot

Surely almost everyone has come to a problem of repeating the actions for some reasons: plain retry (because of some specific error), calling external services once again using some progressive intervals (2 s, 4 s, 8 s….2^n s), making certain number of retries before exiting and etc. The implementation of such “retry” policies are different too (I’m sure some of you are even using GOTO in the languages that do have the ability to use this keyword, tho it’s a known fact to be dangerous!).

But why should you create another bicycle, when there are many and one of them is Polly. Polly is .NET framework that allows you to write fluent policies for Retry, Circuit Breaker, Timeout and other tasks. Polly targets .NET 4.0, .NET 4.5 and .NET Standard 1.0 (coverage: .NET Core, Mono, Xamarin.iOS, Xamarin.Android, UWP, WP8.0+).

To install it just use Nuget Package:

Install-Package Polly

For this post lets do some quickstart with Retry policy. When do you need the one? For example our code block is querying the database and the deadlock appears, the exception will be thrown with the suggestion to retry the operation later; so here is the possible case: you just try to retry the sensible block to finish the operation, deadlocks will happen and you need to handle them in some critical places. For the simplification (to show the actual small working project) we will use some synthetic exception throwing process here and show the retry policy in action in case of that exception.

from the wiki

The code is very simple and you can guess the flow easily because of fluent syntax.

Result — smth like:

4 retries, still unhandled — die.

That’s just one simple scenario, to help you see the more simple approach to retry operations pattern.

Polly’s wiki page has much more information with samples about several other policies it can help you handle.

Give it a try, the guys even have podcast!

--

--