-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathRetry.cs
More file actions
80 lines (68 loc) · 1.32 KB
/
Retry.cs
File metadata and controls
80 lines (68 loc) · 1.32 KB
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
using System.Diagnostics;
namespace SharpTools.Tools.Tests;
[DebuggerStepThrough]
public static class Retry
{
public static async Task Until(int timeLimit, Func<Task<bool>> assertion)
{
var cancellationToken = TestContext.Current.CancellationToken;
using var timeoutWatcher = CancellationTokenUtils.ApplyTimeout(
timeLimit,
ref cancellationToken
);
try
{
while (!cancellationToken.IsCancellationRequested)
{
var result = await assertion();
if (result)
return;
await Task.Delay(TimeSpan.FromMilliseconds(200), cancellationToken);
}
}
catch (TaskCanceledException)
{
if (!timeoutWatcher.TimedOut)
throw;
}
await assertion();
}
public static async Task UntilPasses(Action condition)
{
await UntilPasses(5, condition);
}
public static async Task UntilPasses(Func<Task> condition)
{
await UntilPasses(5, condition);
}
public static async Task UntilPasses(int timeLimit, Func<Task> condition)
{
await Until(
timeLimit,
async () =>
{
try
{
await condition();
return true;
}
catch
{
return false;
}
}
);
await condition();
}
public static async Task UntilPasses(int timeLimit, Action condition)
{
await UntilPasses(
timeLimit,
() =>
{
condition();
return Task.CompletedTask;
}
);
}
}