-
-
Notifications
You must be signed in to change notification settings - Fork 911
/
MicroThread.cs
384 lines (329 loc) · 12.9 KB
/
MicroThread.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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#pragma warning disable SA1405 // Debug.Assert must provide message text
#pragma warning disable SA1402 // File may only contain a single class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Stride.Core.Collections;
using Stride.Core.Diagnostics;
namespace Stride.Core.MicroThreading
{
/// <summary>
/// Represents an execution context managed by a <see cref="Scheduler"/>, that can cooperatively yield execution to another <see cref="MicroThread"/> at any point (usually using async calls).
/// </summary>
public class MicroThread
{
internal ProfilingKey ProfilingKey;
/// <summary>
/// Gets the attached properties to this component.
/// </summary>
public PropertyContainer Tags;
private static long globalCounterId;
private int state;
private CancellationTokenSource cancellationTokenSource;
internal PriorityQueueNode<SchedulerEntry> ScheduledLinkedListNode;
internal LinkedListNode<MicroThread> AllLinkedListNode; // Also used as lock for "CompletionTask"
internal MicroThreadCallbackList Callbacks;
internal SynchronizationContext SynchronizationContext;
public MicroThread(Scheduler scheduler, MicroThreadFlags flags = MicroThreadFlags.None)
{
Id = Interlocked.Increment(ref globalCounterId);
Scheduler = scheduler;
ScheduledLinkedListNode = new PriorityQueueNode<SchedulerEntry>(new SchedulerEntry(this));
AllLinkedListNode = new LinkedListNode<MicroThread>(this);
ScheduleMode = ScheduleMode.Last;
Flags = flags;
Tags = new PropertyContainer(this);
cancellationTokenSource = new CancellationTokenSource();
}
/// <summary>
/// Gets or sets the priority of this <see cref="MicroThread"/>.
/// </summary>
/// <value>
/// The priority.
/// </value>
public long Priority
{
get { return ScheduledLinkedListNode.Value.Priority; }
set
{
if (ScheduledLinkedListNode.Value.Priority != value)
Reschedule(ScheduleMode.First, value);
}
}
/// <summary>
/// Gets the id of this <see cref="MicroThread"/>.
/// </summary>
/// <value>
/// The id.
/// </value>
public long Id { get; private set; }
/// <summary>
/// Gets or sets the name of this <see cref="MicroThread"/>.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets the scheduler associated with this <see cref="MicroThread"/>.
/// </summary>
/// <value>The scheduler associated with this <see cref="MicroThread"/>.</value>
public Scheduler Scheduler { get; private set; }
/// <summary>
/// Gets the state of this <see cref="MicroThread"/>.
/// </summary>
/// <value>The state of this <see cref="MicroThread"/>.</value>
public MicroThreadState State { get { return (MicroThreadState)state; } internal set { state = (int)value; } }
/// <summary>
/// Gets the exception that was thrown by this <see cref="MicroThread"/>.
/// </summary>
/// It could come from either internally, or from <see cref="RaiseException"/> if it was successfully processed.
/// <value>The exception.</value>
public Exception Exception { get; private set; }
/// <summary>
/// Gets the <see cref="MicroThread"/> flags.
/// </summary>
/// <value>
/// The flags.
/// </value>
public MicroThreadFlags Flags { get; private set; }
/// <summary>
/// Gets or sets the <see cref="MicroThread"/> scheduling mode.
/// </summary>
/// <value>
/// The scheduling mode.
/// </value>
public ScheduleMode ScheduleMode { get; set; }
/// <summary>
/// Gets or sets the task that will be executed upon completion (used internally for <see cref="Scheduler.WhenAll"/>)
/// </summary>
internal TaskCompletionSource<int> CompletionTask { get; set; }
/// <summary>
/// A token for listening to the cancellation of the MicroThread.
/// </summary>
public CancellationToken CancellationToken => cancellationTokenSource.Token;
/// <summary>
/// Indicates whether the MicroThread is terminated or not, either in Completed, Canceled or Failed status.
/// </summary>
public bool IsOver
{
get
{
return
State == MicroThreadState.Completed ||
State == MicroThreadState.Canceled ||
State == MicroThreadState.Failed;
}
}
/// <summary>
/// Gets the current micro thread (self).
/// </summary>
/// <value>The current micro thread (self).</value>
public static MicroThread Current
{
get { return Scheduler.CurrentMicroThread; }
}
public void Migrate(Scheduler scheduler)
{
throw new NotImplementedException();
}
public void Remove()
{
throw new NotImplementedException();
}
/// <summary>
/// Starts this <see cref="MicroThread"/> with the specified function.
/// </summary>
/// <param name="microThreadFunction">The micro thread function.</param>
/// <param name="scheduleMode">The schedule mode.</param>
/// <exception cref="System.InvalidOperationException">MicroThread was already started before.</exception>
public void Start(Func<Task> microThreadFunction, ScheduleMode scheduleMode = ScheduleMode.Last)
{
// TODO: Interlocked compare exchange?
if (Interlocked.CompareExchange(ref state, (int)MicroThreadState.Starting, (int)MicroThreadState.None) != (int)MicroThreadState.None)
throw new InvalidOperationException("MicroThread was already started before.");
Action wrappedMicroThreadFunction = async () =>
{
try
{
State = MicroThreadState.Running;
await microThreadFunction();
if (State != MicroThreadState.Running)
throw new InvalidOperationException("MicroThread completed in an invalid state.");
State = MicroThreadState.Completed;
}
catch (OperationCanceledException e)
{
// Exit gracefully on cancellation exceptions
SetException(e);
}
catch (Exception e)
{
Scheduler.Log.Error("Unexpected exception while executing a micro-thread.", e);
SetException(e);
}
finally
{
lock (Scheduler.AllMicroThreads)
{
Scheduler.AllMicroThreads.Remove(AllLinkedListNode);
}
}
};
Action callback = () =>
{
SynchronizationContext = new MicroThreadSynchronizationContext(this);
SynchronizationContext.SetSynchronizationContext(SynchronizationContext);
wrappedMicroThreadFunction();
};
lock (Scheduler.AllMicroThreads)
{
Scheduler.AllMicroThreads.AddLast(AllLinkedListNode);
}
ScheduleContinuation(scheduleMode, callback);
}
/// <summary>
/// Yields to this <see cref="MicroThread"/>.
/// </summary>
/// <returns>Task.</returns>
public async Task Run()
{
Reschedule(ScheduleMode.First, Priority);
var currentScheduler = Scheduler.Current;
if (currentScheduler == Scheduler)
await Scheduler.Yield();
}
/// <summary>
/// Cancels the <see cref="MicroThread"/>.
/// </summary>
public void Cancel()
{
// TODO: If we unschedule the microthread after cancellation, we never give user code the chance to throw OperationCanceledException.
// If we don't, we can't be sure that the MicroThread ends.
// Should we run continuations manually?
// Notify awaitables
cancellationTokenSource.Cancel();
// Unschedule microthread
//lock (Scheduler.scheduledMicroThreads)
//{
// if (ScheduledLinkedListNode.Index != -1)
// {
// Scheduler.scheduledMicroThreads.Remove(ScheduledLinkedListNode);
// }
//}
}
internal void SetException(Exception exception)
{
Exception = exception;
// Depending on if exception was raised from outside or inside, set appropriate state
State = (exception is OperationCanceledException) ? MicroThreadState.Canceled : MicroThreadState.Failed;
}
internal void Reschedule(ScheduleMode scheduleMode, long newPriority)
{
lock (Scheduler.ScheduledEntries)
{
if (ScheduledLinkedListNode.Index != -1)
{
Scheduler.ScheduledEntries.Remove(ScheduledLinkedListNode);
ScheduledLinkedListNode.Value.Priority = newPriority;
Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
}
else
{
ScheduledLinkedListNode.Value.Priority = newPriority;
}
}
}
internal void ScheduleContinuation(ScheduleMode scheduleMode, SendOrPostCallback callback, object callbackState)
{
Debug.Assert(callback != null);
lock (Scheduler.ScheduledEntries)
{
var node = NewCallback();
node.SendOrPostCallback = callback;
node.CallbackState = callbackState;
Callbacks.Add(node);
if (ScheduledLinkedListNode.Index == -1)
Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
}
}
internal void ScheduleContinuation(ScheduleMode scheduleMode, Action callback)
{
Debug.Assert(callback != null);
lock (Scheduler.ScheduledEntries)
{
var node = NewCallback();
node.MicroThreadAction = callback;
Callbacks.Add(node);
if (ScheduledLinkedListNode.Index == -1)
Scheduler.Schedule(ScheduledLinkedListNode, scheduleMode);
}
}
private MicroThreadCallbackNode NewCallback()
{
MicroThreadCallbackNode node;
var pool = Scheduler.CallbackNodePool;
if (Scheduler.CallbackNodePool.Count > 0)
{
var index = pool.Count - 1;
node = pool[index];
pool.RemoveAt(index);
}
else
{
node = new MicroThreadCallbackNode();
}
return node;
}
}
internal class MicroThreadCallbackNode
{
public Action MicroThreadAction;
public SendOrPostCallback SendOrPostCallback;
public object CallbackState;
public MicroThreadCallbackNode Next;
public void Invoke()
{
if (MicroThreadAction != null)
{
MicroThreadAction();
}
else
{
SendOrPostCallback(CallbackState);
}
}
public void Clear()
{
MicroThreadAction = null;
SendOrPostCallback = null;
CallbackState = null;
}
}
internal struct MicroThreadCallbackList
{
public MicroThreadCallbackNode First { get; private set; }
public MicroThreadCallbackNode Last { get; private set; }
public void Add(MicroThreadCallbackNode node)
{
if (First == null)
First = node;
else
Last.Next = node;
Last = node;
}
public bool TakeFirst(out MicroThreadCallbackNode callback)
{
callback = First;
if (First == null)
return false;
First = callback.Next;
callback.Next = null;
return true;
}
}
}