-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFuture.cs
More file actions
1350 lines (1142 loc) · 48.8 KB
/
Future.cs
File metadata and controls
1350 lines (1142 loc) · 48.8 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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using Squared.Util;
using Squared.Util.Bind;
namespace Squared.Threading {
public delegate void OnFutureResolved (IFuture future);
public delegate void OnFutureResolved<T> (Future<T> future);
public delegate void OnFutureResolvedWithData (IFuture future, object userData);
public delegate void OnFutureResolvedWithData<T> (Future<T> future, object userData);
public class FutureException : Exception {
public FutureException (string message, Exception innerException)
: base(message, innerException) {
}
}
public class FutureAlreadyHasResultException : InvalidOperationException {
public readonly IFuture Future;
public FutureAlreadyHasResultException (IFuture future)
: base("Future already has a result") {
Future = future;
}
}
public class FutureHasNoResultException : InvalidOperationException {
public readonly IFuture Future;
public FutureHasNoResultException (IFuture future)
: base("Future does not yet have a result") {
Future = future;
}
}
public class FutureDisposedException : InvalidOperationException {
public readonly IFuture Future;
public FutureDisposedException (IFuture future)
: base("Future is disposed") {
Future = future;
}
}
public class FutureHandlerException : Exception {
public readonly IFuture Future;
public readonly Delegate Handler;
public FutureHandlerException (IFuture future, Delegate handler, Exception innerException)
: base("One of the Future's handlers threw an uncaught exception", innerException) {
Future = future;
Handler = handler;
}
public FutureHandlerException (IFuture future, Delegate handler, string message)
: base(message) {
Future = future;
Handler = handler;
}
}
internal static class FutureHelpers {
// REVIEW: Pretty sure I would like to rewrite this RunInThreadThunk subsystem but not 100% sure how
public static readonly WaitCallback RunInThreadHelper;
static FutureHelpers () {
RunInThreadHelper = _RunInThreadHelper;
}
internal static void _RunInThreadHelper (object state) {
var thunk = (RunInThreadThunk)state;
try {
thunk.Invoke();
} catch (System.Reflection.TargetInvocationException ex) {
// REVIEW: Which cases is this catch block for?
thunk.Fail(ex.InnerException);
} catch (Exception ex) {
thunk.Fail(ex);
}
}
}
internal abstract class RunInThreadThunk {
public abstract void Fail (Exception e);
public abstract void Invoke ();
}
internal sealed class ActionRunInThreadThunk : RunInThreadThunk {
public readonly SignalFuture Future = new SignalFuture();
public Action WorkItem;
public override void Invoke () {
WorkItem();
Future.Complete();
}
public override void Fail (Exception ex) {
Future.Fail(ex);
}
}
internal sealed class FuncRunInThreadThunk<T> : RunInThreadThunk {
public readonly Future<T> Future = new Future<T>();
public Func<T> WorkItem;
public override void Invoke () {
Future.Complete(WorkItem());
}
public override void Fail (Exception ex) {
Future.Fail(ex);
}
}
internal sealed class DynamicRunInThreadThunk : RunInThreadThunk {
public readonly IFuture Future = new Future<object>();
public object[] Arguments;
public Delegate WorkItem;
public override void Invoke () {
Future.Complete(WorkItem.DynamicInvoke(Arguments));
}
public override void Fail (Exception ex) {
Future.Fail(ex);
}
}
public interface IFuture : IDisposable {
bool Failed { get; }
bool Resolved { get; }
bool Completed { get; }
bool CompletedSuccessfully { get; }
bool Disposed { get; }
object Result {
get;
}
object Result2 {
get;
}
Exception Error {
get;
}
Type ResultType {
get;
}
bool GetResult (out object result, out Exception error);
void SetResult (object result, Exception error);
void SetResult2 (object result, ExceptionDispatchInfo errorInfo);
void RegisterHandlers (Action completeHandler, Action disposeHandler);
void RegisterHandlers (OnFutureResolved completeHandler, OnFutureResolved disposeHandler);
void RegisterHandlers (OnFutureResolvedWithData completeHandler, OnFutureResolvedWithData disposeHandler, object userData);
void RegisterOnResolved (Action handler);
void RegisterOnResolved (OnFutureResolved handler);
void RegisterOnResolved (OnFutureResolvedWithData handler, object userData);
void RegisterOnComplete (Action handler);
void RegisterOnComplete (OnFutureResolved handler);
void RegisterOnComplete (OnFutureResolvedWithData handler, object userData);
void RegisterOnDispose (Action handler);
void RegisterOnDispose (OnFutureResolved handler);
void RegisterOnDispose (OnFutureResolvedWithData handler, object userData);
void RegisterOnErrorCheck (Action handler);
bool CopyFrom (IFuture source);
}
public sealed class NoneType {
private NoneType () {
}
public static readonly NoneType None = new NoneType();
}
public sealed class SignalFuture : Future<NoneType> {
public static readonly SignalFuture Signaled = new SignalFuture(true);
public SignalFuture ()
: base() {
}
public SignalFuture (bool signaled)
: base() {
if (signaled)
base.SetResult(NoneType.None, null);
}
}
public static class Future {
public enum State : int {
// REVIEW: I guess Unknown and Disposing are removed because
// you did not want these states to be part of the public API?
Empty = 0,
// Unknown = 1,
CompletedWithValue = 2,
CompletedWithError = 3,
Disposed = 4,
// Disposing = 5;
}
public static Future<T> New<T> () {
return new Future<T>();
}
public static Future<T> New<T> (T value) {
return new Future<T>(value);
}
public static Future<IFuture> WaitForFirst (IEnumerable<IFuture> futures) {
return new WaitForFirstThunk(futures).Composite;
}
public static Future<IFuture> WaitForFirst (params IFuture[] futures) {
return new WaitForFirstThunk(futures).Composite;
}
public static IFuture WaitForAll (IEnumerable<IFuture> futures) {
return new WaitForAllThunk(futures).Composite;
}
public static IFuture WaitForAll (params IFuture[] futures) {
return new WaitForAllThunk(futures).Composite;
}
public static Future<U> RunInThread<U> (Func<U> workItem) {
var thunk = new FuncRunInThreadThunk<U> {
WorkItem = workItem,
};
ThreadPool.QueueUserWorkItem(FutureHelpers.RunInThreadHelper, thunk);
return thunk.Future;
}
public static SignalFuture RunInThread (Action workItem) {
var thunk = new ActionRunInThreadThunk {
WorkItem = workItem,
};
ThreadPool.QueueUserWorkItem(FutureHelpers.RunInThreadHelper, thunk);
return thunk.Future;
}
public static IFuture RunInThread (Delegate workItem, params object[] arguments) {
var thunk = new DynamicRunInThreadThunk {
WorkItem = workItem,
Arguments = arguments
};
ThreadPool.QueueUserWorkItem(FutureHelpers.RunInThreadHelper, thunk);
return thunk.Future;
}
private sealed class WaitForFirstThunk {
public Future<IFuture> Composite = new Future<IFuture>();
public bool Completed;
public WaitForFirstThunk (IEnumerable<IFuture> futures) {
OnFutureResolved handler = null;
// REVIEW: On a theoretical level, I am worried that, if the enumerable is
// empty and not detected by the condition below, or if all futures are null
// then Composite never completes.
// On a practical level, I suspect that it has not happened often. ;)
if (
((futures as System.Collections.IList)?.Count == 0) ||
((futures as Array)?.Length == 0)
) {
// HACK
Composite.Complete(null);
return;
}
foreach (var f in futures) {
if (f == null)
continue;
if (handler == null)
handler = OnResolved;
f.RegisterOnResolved(handler);
if (Completed)
break;
}
}
public void OnResolved (IFuture f) {
lock (this) {
if (Completed)
return;
Completed = true;
}
Composite.Complete(f);
}
}
private sealed class WaitForAllThunk {
public SignalFuture Composite = new SignalFuture();
private bool Initializing = true;
public int TargetCount;
public int DisposeCount, CompleteCount;
public WaitForAllThunk (IEnumerable<IFuture> futures) {
if (
((futures as System.Collections.IList)?.Count == 0) ||
((futures as Array)?.Length == 0)
) {
// HACK
Composite.Complete();
return;
}
OnFutureResolved handler = null;
foreach (var f in futures) {
if (f == null)
continue;
if (handler == null)
handler = OnResolved;
// NOTE: Duplicates will work correctly because we will increment the target count
// twice and then register the handler twice, so the handler will run twice.
TargetCount++;
f.RegisterOnResolved(handler);
}
bool signal;
lock (this) {
Initializing = false;
signal = (DisposeCount + CompleteCount) == TargetCount;
}
if (signal && !Composite.Completed && !Composite.Disposed) {
if (CompleteCount == 0)
Composite.Dispose();
else
Composite.Complete();
}
}
public void OnResolved (IFuture f) {
bool signal = false;
lock (this) {
if (f.Disposed)
DisposeCount++;
else
CompleteCount++;
if (Initializing)
return;
signal = (DisposeCount + CompleteCount) == TargetCount;
}
if (signal && !Composite.Completed && !Composite.Disposed) {
if (CompleteCount == 0)
Composite.Dispose();
else
Composite.Complete();
}
}
}
private sealed class WaitForSingleEventThunk {
public readonly Squared.Util.Bind.BoundMember<EventHandler> Event;
public readonly SignalFuture Future = new SignalFuture();
private readonly EventHandler Handler;
public WaitForSingleEventThunk (Squared.Util.Bind.BoundMember<EventHandler> evt) {
Event = evt;
Handler = OnEvent;
Event.Add(Handler);
// FIXME: Use UserData
Future.RegisterOnDispose((Threading.OnFutureResolved)this.OnDispose);
}
public void OnEvent (object sender, EventArgs args) {
OnDispose(Future);
Future.Complete();
}
public void OnDispose (IFuture future) {
Event.Remove(Handler);
}
}
private sealed class WaitForSingleEventThunk<TEventArgs>
where TEventArgs : System.EventArgs {
public readonly Squared.Util.Bind.BoundMember<EventHandler<TEventArgs>> Event;
public readonly Future<TEventArgs> Future = new Future<TEventArgs>();
private readonly EventHandler<TEventArgs> Handler;
public WaitForSingleEventThunk (Squared.Util.Bind.BoundMember<EventHandler<TEventArgs>> evt) {
Event = evt;
Handler = OnEvent;
Event.Add(Handler);
// FIXME: Use UserData
Future.RegisterOnDispose((Threading.OnFutureResolved)this.OnDispose);
}
public void OnEvent (object sender, TEventArgs args) {
OnDispose(Future);
Future.SetResult(args, null);
}
public void OnDispose (IFuture future) {
Event.Remove(Handler);
}
}
public static Future<TEventArgs> WaitForSingleEvent<TEventArgs>
(Squared.Util.Bind.BoundMember<EventHandler<TEventArgs>> evt)
where TEventArgs : System.EventArgs
{
return (new WaitForSingleEventThunk<TEventArgs>(evt)).Future;
}
public static SignalFuture WaitForSingleEvent(Squared.Util.Bind.BoundMember<EventHandler> evt) {
return (new WaitForSingleEventThunk(evt)).Future;
}
public static Future<TEventArgs> WaitForSingleEvent<TEventArgs>
(Expression<Action<EventHandler<TEventArgs>>> evt)
where TEventArgs : System.EventArgs {
var bm = Squared.Util.Bind.BoundMember.New(evt);
return WaitForSingleEvent(bm);
}
public static SignalFuture WaitForSingleEvent (Expression<Action<EventHandler>> evt) {
var bm = Squared.Util.Bind.BoundMember.New(evt);
return WaitForSingleEvent(bm);
}
}
public class Future<T> : IDisposable, IFuture {
private enum HandlerType : byte {
Resolved,
Completed,
Disposed
}
private readonly struct Handler {
public readonly HandlerType Type;
public readonly Delegate Delegate;
public readonly object UserData;
public Handler (HandlerType type, Delegate handler, object userData) {
Type = type;
Delegate = handler;
UserData = userData;
}
public void Invoke (Future<T> future) {
try {
if (Delegate is OnFutureResolved<T> typed) {
typed(future);
} else if (Delegate is OnFutureResolved untyped) {
untyped(future);
} else if (Delegate is OnFutureResolvedWithData<T> withData) {
withData(future, UserData);
} else if (Delegate is OnFutureResolvedWithData withDataUntyped) {
withDataUntyped(future, UserData);
} else if (Delegate is Action action) {
action();
} else {
throw new FutureHandlerException(future, Delegate, "Invalid future handler");
}
} catch (Exception exc) {
throw new FutureHandlerException(future, Delegate, exc);
}
}
}
private static readonly int ProcessorCount;
private const int State_Empty = (int)Future.State.Empty;
private const int State_Indeterminate = 1;
private const int State_CompletedWithValue = (int)Future.State.CompletedWithValue;
private const int State_CompletedWithError = (int)Future.State.CompletedWithError;
private const int State_Disposed = (int)Future.State.Disposed;
private const int State_Disposing = 5;
private volatile int _State = State_Empty;
private DenseList<Handler> _Handlers;
private object _Error = null;
private Action _OnErrorChecked = null;
private T _Result = default(T);
public override string ToString () {
int state = _State;
var result = _Result;
var error = InternalError;
string stateText = "??";
switch (state) {
case State_Empty:
stateText = "Empty";
break;
case State_Indeterminate:
stateText = "Indeterminate";
break;
case State_CompletedWithValue:
stateText = "CompletedWithValue";
break;
case State_CompletedWithError:
stateText = "CompletedWithError";
break;
case State_Disposed:
case State_Disposing:
stateText = "Disposed";
break;
}
return String.Format("<Future<{3}> ({0}) r={1} e={2}>", stateText, result, error, typeof(T).Name);
}
/// <summary>
/// Creates a future that is not yet completed
/// </summary>
public Future () {
}
/// <summary>
/// Creates a future that is already completed with a value
/// </summary>
public Future (T value) {
this.SetResult(value, null);
}
static Future () {
ProcessorCount = Environment.ProcessorCount;
}
private static void SpinWait (int iterationCount) {
if ((iterationCount < 5) && (ProcessorCount > 1)) {
Thread.SpinWait(7 * iterationCount);
} else if (iterationCount < 7) {
Thread.Sleep(0);
} else {
Thread.Sleep(1);
}
}
private void InvokeHandlers (HandlerType type) {
var c = _Handlers.Count;
if (c <= 0)
return;
try {
for (int i = 0; i < c; i++) {
ref var handler = ref _Handlers.Item(i);
if ((handler.Type == type) || (handler.Type == HandlerType.Resolved))
handler.Invoke(this);
}
} finally {
_Handlers.Clear();
}
}
void OnErrorCheck () {
var ec = Interlocked.Exchange(ref _OnErrorChecked, null);
if (ec != null)
ec();
}
/// <summary>
/// Registers a handler that will be invoked when the error status of this future is checked.
/// You can use this to identify whether a future has been abandoned.
/// </summary>
public void RegisterOnErrorCheck (Action handler) {
Action newHandler;
int iterations = 1;
while (true) {
var oldHandler = _OnErrorChecked;
if (oldHandler != null) {
newHandler = () => {
oldHandler();
handler();
};
} else {
newHandler = handler;
}
if (Interlocked.CompareExchange(ref _OnErrorChecked, newHandler, oldHandler) == oldHandler)
break;
SpinWait(iterations);
iterations += 1;
}
}
private void ClearIndeterminate (int newState) {
if (Interlocked.CompareExchange(ref _State, newState, State_Indeterminate) != State_Indeterminate)
throw new ThreadStateException("Future state was not indeterminate");
}
private int TrySetIndeterminate () {
int state;
int iterations = 1;
while (true) {
state = Interlocked.CompareExchange(ref _State, State_Indeterminate, State_Empty);
if (state != State_Indeterminate)
break;
SpinWait(iterations++);
}
return state;
}
/// <returns>Whether the future is already complete and handlers were run</returns>
private bool RegisterHandler_Impl (Delegate handler, HandlerType type, object userData = null) {
if (handler == null)
return false;
var item = new Handler(type, handler, userData);
int oldState = TrySetIndeterminate();
if (oldState == State_Empty) {
_Handlers.Add(item);
ClearIndeterminate(State_Empty);
return false;
}
var runCompletedHandler = (oldState == State_CompletedWithValue) ||
(oldState == State_CompletedWithError);
var runDisposedHandler = (oldState == State_Disposed) ||
(oldState == State_Disposing);
if (!runCompletedHandler && !runDisposedHandler)
throw new ThreadStateException("Failed to register future handler due to a thread state error");
switch (type) {
case HandlerType.Completed:
if (runCompletedHandler) {
item.Invoke(this);
return true;
}
break;
case HandlerType.Disposed:
if (runDisposedHandler) {
item.Invoke(this);
return true;
}
break;
case HandlerType.Resolved:
if (runCompletedHandler || runDisposedHandler) {
item.Invoke(this);
return true;
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(type));
}
return false;
}
/// <summary>
/// Registers a pair of handlers to be notified upon future completion and disposal, respectively.
/// </summary>
public void RegisterHandlers (Action onComplete, Action onDispose) {
if (onComplete == onDispose) {
RegisterHandler_Impl(onComplete, HandlerType.Resolved);
return;
}
// FIXME: Set state to indeterminate once instead of twice
// REVIEW: I think that it would be possible to set state to indeterminate only once
// by splitting RegisterHandler_Impl in two:
// * a Disposable struct that would call TrySetIndeterminate on instantiation, and ClearIndeterminate on Dispose
// * a function that does the work of registering or running the handler
if (!RegisterHandler_Impl(onComplete, HandlerType.Completed))
RegisterHandler_Impl(onDispose, HandlerType.Disposed);
}
/// <summary>
/// Registers a pair of handlers to be notified upon future completion and disposal, respectively.
/// </summary>
public void RegisterHandlers (OnFutureResolved<T> onComplete, OnFutureResolved onDispose) {
// FIXME: Set state to indeterminate once instead of twice
if (!RegisterHandler_Impl(onComplete, HandlerType.Completed))
RegisterHandler_Impl(onDispose, HandlerType.Disposed);
}
/// <summary>
/// Registers a pair of handlers to be notified upon future completion and disposal, respectively.
/// </summary>
void IFuture.RegisterHandlers (OnFutureResolved onComplete, OnFutureResolved onDispose) {
if (onComplete == onDispose) {
RegisterHandler_Impl(onComplete, HandlerType.Resolved);
return;
}
// FIXME: Set state to indeterminate once instead of twice
if (!RegisterHandler_Impl(onComplete, HandlerType.Completed))
RegisterHandler_Impl(onDispose, HandlerType.Disposed);
}
/// <summary>
/// Registers a pair of handlers to be notified upon future completion and disposal, respectively.
/// </summary>
void IFuture.RegisterHandlers (OnFutureResolvedWithData onComplete, OnFutureResolvedWithData onDispose, object userData) {
if (onComplete == onDispose) {
RegisterHandler_Impl(onComplete, HandlerType.Resolved, userData);
return;
}
// FIXME: Set state to indeterminate once instead of twice
if (!RegisterHandler_Impl(onComplete, HandlerType.Completed, userData))
RegisterHandler_Impl(onDispose, HandlerType.Disposed, userData);
}
void IFuture.RegisterOnResolved (OnFutureResolved handler) {
RegisterHandler_Impl(handler, HandlerType.Resolved, false);
}
void IFuture.RegisterOnResolved (Action handler) {
RegisterHandler_Impl(handler, HandlerType.Resolved, false);
}
/// <summary>
/// Registers a handler to be notified upon future completion or disposal.
/// </summary>
public void RegisterOnResolved (OnFutureResolved handler) {
RegisterHandler_Impl(handler, HandlerType.Resolved);
}
/// <summary>
/// Registers a handler to be notified upon future completion or disposal.
/// </summary>
public void RegisterOnResolved2 (OnFutureResolved<T> handler) {
RegisterHandler_Impl(handler, HandlerType.Resolved);
}
/// <summary>
/// Registers a handler to be notified upon future completion or disposal.
/// </summary>
public void RegisterOnResolved (OnFutureResolvedWithData handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Resolved, userData);
}
/// <summary>
/// Registers a handler to be notified upon future completion or disposal.
/// </summary>
public void RegisterOnResolved2 (OnFutureResolvedWithData<T> handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Resolved, userData);
}
/// <summary>
/// Registers a handler to be notified upon future completion. If the future is disposed, this will not run.
/// </summary>
public void RegisterOnComplete (Action handler) {
RegisterHandler_Impl(handler, HandlerType.Completed);
}
/// <summary>
/// Registers a handler to be notified upon future completion. If the future is disposed, this will not run.
/// </summary>
public void RegisterOnComplete (OnFutureResolved handler) {
RegisterHandler_Impl(handler, HandlerType.Completed);
}
/// <summary>
/// Registers a handler to be notified upon future completion. If the future is disposed, this will not run.
/// </summary>
public void RegisterOnComplete2 (OnFutureResolved<T> handler) {
RegisterHandler_Impl(handler, HandlerType.Completed);
}
/// <summary>
/// Registers a handler to be notified upon future completion. If the future is disposed, this will not run.
/// </summary>
public void RegisterOnComplete (OnFutureResolvedWithData handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Completed, userData);
}
/// <summary>
/// Registers a handler to be notified upon future completion. If the future is disposed, this will not run.
/// </summary>
public void RegisterOnComplete (OnFutureResolvedWithData<T> handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Completed, userData);
}
/// <summary>
/// Registers a handlers to be notified upon future disposal. If the future is completed, this will not run.
/// </summary>
public void RegisterOnDispose (Action handler) {
RegisterHandler_Impl(handler, HandlerType.Disposed);
}
/// <summary>
/// Registers a handlers to be notified upon future disposal. If the future is completed, this will not run.
/// </summary>
public void RegisterOnDispose (OnFutureResolved handler) {
RegisterHandler_Impl(handler, HandlerType.Disposed);
}
/// <summary>
/// Registers a handlers to be notified upon future disposal. If the future is completed, this will not run.
/// </summary>
public void RegisterOnDispose (OnFutureResolvedWithData<T> handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Disposed, userData);
}
/// <summary>
/// Registers a handlers to be notified upon future disposal. If the future is completed, this will not run.
/// </summary>
public void RegisterOnDispose (OnFutureResolvedWithData handler, object userData) {
RegisterHandler_Impl(handler, HandlerType.Disposed, userData);
}
/// <summary>
/// Returns true if the future has been disposed or is in the process of being disposed.
/// </summary>
public bool Disposed {
get {
int state = _State;
return (state == State_Disposed) || (state == State_Disposing);
}
}
/// <summary>
/// Returns true if the future has been completed or disposed.
/// Note that if the future is currently being completed, this may return false.
/// </summary>
public bool Resolved {
get {
int state = _State;
return (state != State_Indeterminate) && (state != State_Empty);
}
}
/// <summary>
/// Returns true if the future has been completed.
/// Note that if the future is currently being completed, this may return false.
/// </summary>
public bool Completed {
get {
int state = _State;
return (state == State_CompletedWithValue) || (state == State_CompletedWithError);
}
}
/// <summary>
/// Returns true if the future has been completed with a result instead of an error.
/// Note that if the future is currently being completed, this may return false.
/// </summary>
public bool CompletedSuccessfully {
get {
OnErrorCheck();
return _State == State_CompletedWithValue;
}
}
/// <summary>
/// Returns true if the future has been completed but was completed with an error.
/// Note that if the future is currently being completed, this may return false.
/// </summary>
public bool Failed {
get {
OnErrorCheck();
return _State == State_CompletedWithError;
}
}
Type IFuture.ResultType {
get {
return typeof(T);
}
}
object IFuture.Result {
get {
return this.Result;
}
}
object IFuture.Result2 {
get {
return this.Result2;
}
}
private Exception InternalError {
get {
return (_Error is ExceptionDispatchInfo edi)
? edi.SourceException
: (Exception)_Error;
}
}
public Future.State State {
get {
int state = _State;
if (state == State_Disposing)
return Future.State.Disposed;
// FIXME: Is this right?
else if (state == State_Indeterminate)
return Future.State.Empty;
return (Future.State)state;
}
}
/// <summary>
/// Returns the exception that caused the future to fail, if it has failed.
/// </summary>
public Exception Error {
get {
int state = _State;
if (state == State_CompletedWithValue) {
return null;
} else if (state == State_CompletedWithError) {
OnErrorCheck();
return InternalError;
} else if ((state == State_Disposed) || (state == State_Disposing)) {
return null;
} else
throw new FutureHasNoResultException(this);
}
}
/// <summary>
/// Returns the future's result if it contains one.
/// If it failed, a FutureException will be thrown, with the original exception as its InnerException.
/// </summary>
public ref readonly T Result {
get {
int state = _State;
if (state == State_CompletedWithValue) {
return ref _Result;
} else if (state == State_CompletedWithError) {
OnErrorCheck();
throw new FutureException("Future's result was an error", InternalError);
} else if ((state == State_Disposed) || (state == State_Disposing)) {
throw new FutureDisposedException(this);
} else
throw new FutureHasNoResultException(this);
}
}
/// <summary>
/// Returns the future's result if it contains one.
/// If it failed, the exception responsible will be rethrown with its stack preserved (if possible).
/// </summary>
public ref readonly T Result2 {
get {
int state = _State;
if (state == State_CompletedWithValue) {
return ref _Result;
} else if (state == State_CompletedWithError) {
OnErrorCheck();
if (_Error is ExceptionDispatchInfo edi) {
edi.Throw();
throw new FutureException("Failed to rethrow exception from dispatch info", edi.SourceException);
} else
throw new FutureException("Future's result was an error", (Exception)_Error);
} else if ((state == State_Disposed) || (state == State_Disposing)) {
throw new FutureDisposedException(this);
} else
throw new FutureHasNoResultException(this);
}
}
bool IFuture.CopyFrom (IFuture source) {
var tSelf = source as Future<T>;
if (tSelf != null)
return CopyFrom(tSelf);
else {
object r;
Exception e;
if (source.GetResult(out r, out e)) {
if (r == null)
SetResult(default(T), e);
else
SetResult((T)r, e);
return true;
}
return false;
}
}
/// <summary>
/// Attempts to the current state of the source future to this future.
/// May fail for various reasons (for example, this future is already completed).
/// </summary>
/// <returns>true if the copy was successful.</returns>
public bool CopyFrom (Future<T> source) {
var state = source._State;
// FIXME: Wait if it's indeterminate state
if ((state == State_Indeterminate) || (state == State_Empty))
return false;
if (!SetResultPrologue())
return false;