-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathRetry.linq
62 lines (54 loc) · 991 Bytes
/
Retry.linq
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
<Query Kind="Program">
<Namespace>System.Threading.Tasks</Namespace>
</Query>
//Quick lambda to retry execution n amount of times and backoff
async Task Main()
{
Retry(3, TimeSpan.FromSeconds(2), () =>
{
});
await RetryAsync(3, TimeSpan.FromSeconds(2), () =>
{
//We cant return void for async
return Task.FromResult(0);
});
}
// You can define other methods, fields, classes and namespaces here
public static void Retry(int times, TimeSpan delay, Action action)
{
int retries = 0;
int backoff = 1;
while (true)
{
try
{
retries++;
action();
break;
}
catch when (retries < times)
{
Task.Delay(delay*backoff).Wait();
backoff+=backoff;
}
}
}
public static async Task RetryAsync(int times, TimeSpan delay, Func<Task> func)
{
int retries = 0;
int backoff = 1;
while (true)
{
try
{
retries++;
await func();
break;
}
catch when (retries < times)
{
await Task.Delay(delay * backoff);
backoff += backoff;
}
}
}