-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCancelableCompletionSource.cs
More file actions
193 lines (164 loc) · 5.89 KB
/
Copy pathCancelableCompletionSource.cs
File metadata and controls
193 lines (164 loc) · 5.89 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using UnityEngine;
namespace Screenplay
{
public class CancelableCompletionSource<T>
{
private readonly Action<object> _onExternalCancel;
private readonly List<Cancellation> _cancellations = new(4);
private readonly List<Action> _continuations = new(4);
private T _currentVal = default!;
private State _state;
private enum State
{
Idle,
Successful,
Canceled
}
public CancelableCompletionSource()
{
_onExternalCancel = o =>
{
var continuation = (Action)o;
int i = _continuations.IndexOf(continuation);
// We're not removing, as it makes signaling a bit more complex
_continuations[i] = static () => { };
_cancellations[i] = Cancellation.None;
try
{
continuation();
}
catch (Exception e)
{
Debug.LogException(e);
}
};
}
private void CheckThread()
{
if (PlayerLoopHelper.IsMainThread == false)
throw new InvalidOperationException("Cannot be used from multiple threads");
}
public Awaitable AwaitResult(Cancellation cancellation) => new(this, cancellation);
public bool IsCompleted([NotNullWhen(true)] out T? val)
{
if (_state == State.Successful)
{
val = _currentVal!;
return true;
}
val = default;
return false;
}
private void RegisterNewContinuation(Action continuation, Cancellation cancellation)
{
CheckThread();
cancellation.ThrowIfCancellationRequested();
switch (_state)
{
case State.Idle:
_continuations.Add(continuation);
_cancellations.Add(cancellation);
cancellation.Register(_onExternalCancel, continuation);
break;
case State.Successful:
try
{
continuation();
}
catch (Exception e)
{
Debug.LogException(e);
}
break;
case State.Canceled:
throw new TaskCanceledException();
default:
throw new ArgumentOutOfRangeException();
}
}
public void SetResult(T value)
{
CheckThread();
if (_state != State.Idle)
throw new InvalidOperationException();
_currentVal = value;
_state = State.Successful;
Release();
}
public void SetCanceled()
{
CheckThread();
if (_state != State.Idle)
throw new InvalidOperationException();
_state = State.Canceled;
Release();
}
private void Release()
{
for (int i = 0; i < _continuations.Count; i++)
{
_cancellations[i].Unregister(_onExternalCancel, _continuations[i]);
// The above may or may not run the _continuations[i] method, we shouldn't double-run it,
// so fetch it again as it'll be replaced by a no-op if it ran
var continuation = _continuations[i];
_cancellations[i] = default;
_continuations[i] = static () => { };
try
{
continuation();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
_continuations.Clear();
_cancellations.Clear();
}
public readonly struct Awaitable
{
readonly CancelableCompletionSource<T> provider;
readonly Cancellation ct;
public Awaitable(CancelableCompletionSource<T> provider, Cancellation ct = default)
{
this.provider = provider ?? throw new ArgumentNullException(nameof(provider));
this.ct = ct;
}
public Awaiter GetAwaiter() => new(provider, ct);
public readonly struct Awaiter : ICriticalNotifyCompletion
{
private readonly CancelableCompletionSource<T> _provider;
private readonly Cancellation _ct;
public Awaiter(CancelableCompletionSource<T> provider, Cancellation ct)
{
_provider = provider;
_ct = ct;
}
public bool IsCompleted => false;
public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation);
public void UnsafeOnCompleted(Action continuation) => _provider.RegisterNewContinuation(continuation, _ct);
public T GetResult()
{
_ct.ThrowIfCancellationRequested();
switch (_provider._state)
{
case State.Idle:
throw new InvalidOperationException();
case State.Successful:
return _provider._currentVal;
case State.Canceled:
throw new TaskCanceledException();
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}
}