forked from parse-community/Parse-SDK-dotNET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCancellationTokenSource.cs
88 lines (81 loc) · 2.5 KB
/
CancellationTokenSource.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace System.Threading {
/// <summary>
/// A provider for <see cref="CancellationToken"/>s. Use the CancellationTokenSource to
/// notify consumers of its token that they should cancel any ongoing operations.
/// </summary>
public sealed class CancellationTokenSource {
private object mutex = new object();
private Action actions;
internal CancellationTokenRegistration Register(Action action) {
lock (mutex) {
actions += action;
return new CancellationTokenRegistration(this, action);
}
}
internal void Unregister(Action action) {
lock (mutex) {
actions -= action;
}
}
private bool isCancellationRequested;
internal bool IsCancellationRequested {
get {
lock (mutex) {
return isCancellationRequested;
}
}
}
/// <summary>
/// Gets a cancellation token linked to this CancellationTokenSource.
/// </summary>
public CancellationToken Token {
get {
return new CancellationToken(this);
}
}
/// <summary>
/// Notifies consumers of the token that cancellation was requested.
/// </summary>
public void Cancel() {
Cancel(false);
}
/// <summary>
/// Notifies consumers of the token that cancellation was requested.
/// If <paramref name="throwOnFirstException"/> is true, any exception thrown by a
/// handler of the cancellation request will cause processing of the cancellation
/// to halt and the exception will propagate immediately to the caller.
/// </summary>
/// <param name="throwOnFirstException">Whether to throw on first exception.</param>
public void Cancel(bool throwOnFirstException) {
lock (mutex) {
isCancellationRequested = true;
if (actions != null) {
try {
if (throwOnFirstException) {
actions();
} else {
foreach (var del in actions.GetInvocationList()) {
var exceptions = new List<Exception>();
try {
((Action)del)();
} catch (Exception ex) {
exceptions.Add(ex);
}
if (exceptions.Count > 0) {
throw new AggregateException(exceptions);
}
}
}
} finally {
actions = null;
}
}
}
}
}
}