-
Notifications
You must be signed in to change notification settings - Fork 128
/
Demo01_RetryNTimes.cs
99 lines (85 loc) · 3.72 KB
/
Demo01_RetryNTimes.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;
namespace PollyDemos;
/// <summary>
/// <para>
/// Demonstrates the Retry strategy coming into action. <br/>
/// Loops through a series of HTTP requests, keeping track of each requested <br/>
/// item and reporting server failures when encountering exceptions.
/// </para>
/// <para>
/// Observations:
/// <list type="bullet">
/// <item>There's no wait among these retries. It can be appropriate sometimes.</item>
/// <item>In this case, no wait hasn't given underlying system time to recover, so calls still fail despite retries.</item>
/// </list>
/// </para>
/// <para>
/// How to read the demo logs:
/// <list type="bullet">
/// <item>"Response: ... request #N(...)": Response received on time.</item>
/// </list>
/// </para>
/// </summary>
public class Demo01_RetryNTimes : DemoBase
{
public override string Description =>
"This demo demonstrates a first Retry. It retries three times, immediately.";
public override async Task ExecuteAsync(CancellationToken cancellationToken, IProgress<DemoProgress> progress)
{
ArgumentNullException.ThrowIfNull(progress);
EventualSuccesses = 0;
Retries = 0;
EventualFailures = 0;
TotalRequests = 0;
PrintHeader(progress);
// Define our strategy:
var strategy = new ResiliencePipelineBuilder().AddRetry(new()
{
ShouldHandle = new PredicateBuilder().Handle<Exception>(),
MaxRetryAttempts = 3, // Retry up to 3 times
OnRetry = args =>
{
// Due to how we have defined ShouldHandle, this delegate is called only if an exception occurred.
// Note the ! sign (null-forgiving operator) at the end of the command.
var exception = args.Outcome.Exception!; // The Exception property is nullable
// Tell the user what happened
progress.Report(ProgressWithMessage($"Strategy logging: {exception.Message}", Color.Yellow));
Retries++;
return default;
}
}).Build();
var client = new HttpClient();
var internalCancel = false;
while (!(internalCancel || cancellationToken.IsCancellationRequested))
{
TotalRequests++;
try
{
// Retry the following call according to the strategy.
// The cancellationToken passed in to ExecuteAsync() enables the strategy to cancel retries when the token is signalled.
await strategy.ExecuteAsync(async token =>
{
// This code is executed within the strategy
var responseBody = await IssueRequestAndProcessResponseAsync(client, token);
progress.Report(ProgressWithMessage($"Response : {responseBody}", Color.Green));
EventualSuccesses++;
}, cancellationToken);
}
catch (Exception e)
{
progress.Report(ProgressWithMessage($"Request {TotalRequests} eventually failed with: {e.Message}", Color.Red));
EventualFailures++;
}
await Task.Delay(TimeSpan.FromSeconds(0.5), cancellationToken);
internalCancel = ShouldTerminateByKeyPress();
}
}
public override Statistic[] LatestStatistics => new Statistic[]
{
new("Total requests made", TotalRequests),
new("Requests which eventually succeeded", EventualSuccesses, Color.Green),
new("Retries made to help achieve success", Retries, Color.Yellow),
new("Requests which eventually failed", EventualFailures, Color.Red),
};
}