-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGoodCitizen.cs
47 lines (41 loc) · 1.6 KB
/
GoodCitizen.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
using System;
using System.Threading;
using System.Threading.Tasks;
class GoodCitizen : IRunnable
{
public async Task Run()
{
using var tokenSource = new CancellationTokenSource();
this.PrintStart();
await Task.Delay(TimeSpan.FromDays(1))
.WithCancellation(tokenSource.Token)
.IgnoreCancellation();
this.PrintEnd();
this.PrintStart();
tokenSource.CancelAfter(TimeSpan.FromSeconds(2));
await Task.Delay(TimeSpan.FromDays(1))
.WithCancellation(tokenSource.Token)
.IgnoreCancellation();
this.PrintEnd();
}
}
static class GoodCitizenTaskExtensions
{
public static async Task WithCancellation(this Task task, CancellationToken token = default)
{
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
linkedTokenSource.CancelAfter(TimeSpan.FromSeconds(10));
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
using var registration = linkedTokenSource.Token.Register(state =>
{
((TaskCompletionSource<object>)state).TrySetResult(null);
}, tcs, useSynchronizationContext: false);
var resultTask = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (resultTask == tcs.Task)
{
// Operation cancelled
throw new OperationCanceledException(token.IsCancellationRequested ? token : linkedTokenSource.Token);
}
await task.ConfigureAwait(false);
}
}