Skip to content

Commit bf44d97

Browse files
authored
Polly - Dot net Interactive notebook
1 parent f0e8320 commit bf44d97

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

polly.dib

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!csharp
2+
3+
#r "nuget: Polly, 7.2.3"
4+
using Polly;
5+
using System.IO;
6+
7+
#!csharp
8+
9+
string filename = @"C:\tmp\in.txt";
10+
11+
var fileRetryPolicy = Polly.Policy.Handle<System.IO.FileNotFoundException>().WaitAndRetry(5, retryAttempt => {Console.WriteLine("retry " + retryAttempt); return TimeSpan.FromSeconds((Math.Pow(2, retryAttempt))); });
12+
13+
// Writing to file with a retry that fails and is not handled if the file is readonly because the policy does not handle System.UnauthorizedAccessException
14+
// fileRetryPolicy.Execute(() => File.AppendAllText(filename, DateTime.UtcNow.ToString() + Environment.NewLine));
15+
16+
string contents = fileRetryPolicy.Execute<string>(() => { return File.ReadAllText(filename);});
17+
Console.WriteLine(contents);
18+
19+
var fileUnauthorizedPolicy = Polly.Policy.Handle<System.UnauthorizedAccessException>().Fallback( () => Console.WriteLine("File is locked readonly"));
20+
fileUnauthorizedPolicy.Execute(() => File.AppendAllText(filename, DateTime.UtcNow.ToString() + Environment.NewLine));

0 commit comments

Comments
 (0)