-
Notifications
You must be signed in to change notification settings - Fork 789
/
async.fs
2383 lines (1981 loc) · 100 KB
/
async.fs
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace Microsoft.FSharp.Control
#nowarn "40"
#nowarn "52" // The value has been copied to ensure the original is not mutated by this operation
open System
open System.Diagnostics
open System.Reflection
open System.Runtime.CompilerServices
open System.Runtime.ExceptionServices
open System.Threading
open System.Threading.Tasks
open Microsoft.FSharp.Core
open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators
open Microsoft.FSharp.Control
open Microsoft.FSharp.Collections
type LinkedSubSource(cancellationToken: CancellationToken) =
let failureCTS = new CancellationTokenSource()
let linkedCTS =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, failureCTS.Token)
member _.Token = linkedCTS.Token
member _.Cancel() =
failureCTS.Cancel()
member _.Dispose() =
linkedCTS.Dispose()
failureCTS.Dispose()
interface IDisposable with
member this.Dispose() =
this.Dispose()
/// Global mutable state used to associate Exception
[<AutoOpen>]
module ExceptionDispatchInfoHelpers =
let associationTable = ConditionalWeakTable<exn, ExceptionDispatchInfo>()
type ExceptionDispatchInfo with
member edi.GetAssociatedSourceException() =
let exn = edi.SourceException
// Try to store the entry in the association table to allow us to recover it later.
try
associationTable.Add(exn, edi)
with _ ->
()
exn
// Capture, but prefer the saved information if available
[<DebuggerHidden>]
static member RestoreOrCapture exn =
match associationTable.TryGetValue exn with
| true, edi -> edi
| _ -> ExceptionDispatchInfo.Capture exn
member inline edi.ThrowAny() =
edi.Throw()
Unchecked.defaultof<'T> // Note, this line should not be reached, but gives a generic return type
// F# don't always take tailcalls to functions returning 'unit' because this
// is represented as type 'void' in the underlying IL.
// Hence we don't use the 'unit' return type here, and instead invent our own type.
[<NoEquality; NoComparison>]
type AsyncReturn =
| AsyncReturn
static member inline Fake() =
Unchecked.defaultof<AsyncReturn>
type cont<'T> = ('T -> AsyncReturn)
type econt = (ExceptionDispatchInfo -> AsyncReturn)
type ccont = (OperationCanceledException -> AsyncReturn)
[<AllowNullLiteral>]
type Trampoline() =
[<Literal>]
static let bindLimitBeforeHijack = 300
[<ThreadStatic; DefaultValue>]
static val mutable private thisThreadHasTrampoline: bool
static member ThisThreadHasTrampoline = Trampoline.thisThreadHasTrampoline
let mutable storedCont = None
let mutable storedExnCont = None
let mutable bindCount = 0
/// Use this trampoline on the synchronous stack if none exists, and execute
/// the given function. The function might write its continuation into the trampoline.
[<DebuggerHidden>]
member _.Execute(firstAction: unit -> AsyncReturn) =
let thisThreadHadTrampoline = Trampoline.thisThreadHasTrampoline
Trampoline.thisThreadHasTrampoline <- true
try
let mutable keepGoing = true
let mutable action = firstAction
while keepGoing do
try
action () |> ignore
match storedCont with
| None -> keepGoing <- false
| Some cont ->
storedCont <- None
action <- cont
// Catch exceptions at the trampoline to get a full .StackTrace entry
// This is because of this problem https://stackoverflow.com/questions/5301535/exception-call-stack-truncated-without-any-re-throwing
// where only a limited number of stack frames are included in the .StackTrace property
// of a .NET exception when it is thrown, up to the first catch handler.
//
// So when running async code, there aren't any intermediate catch handlers (though there
// may be intermediate try/finally frames), there is just this one catch handler at the
// base of the stack.
//
// If an exception is thrown we must have storedExnCont via OnExceptionRaised.
with exn ->
match storedExnCont with
| None ->
// Here, the exception escapes the trampoline. This should not happen since all
// exception-generating code should use ProtectCode. However some
// direct uses of combinators (not using async {...}) may cause
// code to execute unprotected, e.g. async.While((fun () -> failwith ".."), ...) executes the first
// guardExpr unprotected.
reraise ()
| Some econt ->
storedExnCont <- None
let edi = ExceptionDispatchInfo.RestoreOrCapture exn
action <- (fun () -> econt edi)
finally
Trampoline.thisThreadHasTrampoline <- thisThreadHadTrampoline
AsyncReturn.Fake()
/// Increment the counter estimating the size of the synchronous stack and
/// return true if time to jump on trampoline.
member _.IncrementBindCount() =
bindCount <- bindCount + 1
bindCount >= bindLimitBeforeHijack
/// Prepare to abandon the synchronous stack of the current execution and save the continuation in the trampoline.
member _.Set action =
assert storedCont.IsNone
bindCount <- 0
storedCont <- Some action
AsyncReturn.Fake()
/// Save the exception continuation during propagation of an exception, or prior to raising an exception
member _.OnExceptionRaised(action: econt) =
assert storedExnCont.IsNone
storedExnCont <- Some action
type TrampolineHolder() =
let mutable trampoline = null
// On-demand allocate this delegate and keep it in the trampoline holder.
let mutable sendOrPostCallbackWithTrampoline: SendOrPostCallback = null
let getSendOrPostCallbackWithTrampoline (this: TrampolineHolder) =
match sendOrPostCallbackWithTrampoline with
| null ->
sendOrPostCallbackWithTrampoline <-
SendOrPostCallback(fun o ->
let f = unbox<unit -> AsyncReturn> o
// Reminder: the ignore below ignores an AsyncReturn.
this.ExecuteWithTrampoline f |> ignore)
| _ -> ()
sendOrPostCallbackWithTrampoline
// On-demand allocate this delegate and keep it in the trampoline holder.
let mutable waitCallbackForQueueWorkItemWithTrampoline: WaitCallback = null
let getWaitCallbackForQueueWorkItemWithTrampoline (this: TrampolineHolder) =
match waitCallbackForQueueWorkItemWithTrampoline with
| null ->
waitCallbackForQueueWorkItemWithTrampoline <-
WaitCallback(fun o ->
let f = unbox<unit -> AsyncReturn> o
this.ExecuteWithTrampoline f |> ignore)
| _ -> ()
waitCallbackForQueueWorkItemWithTrampoline
// On-demand allocate this delegate and keep it in the trampoline holder.
let mutable threadStartCallbackForStartThreadWithTrampoline: ParameterizedThreadStart =
null
let getThreadStartCallbackForStartThreadWithTrampoline (this: TrampolineHolder) =
match threadStartCallbackForStartThreadWithTrampoline with
| null ->
threadStartCallbackForStartThreadWithTrampoline <-
ParameterizedThreadStart(fun o ->
let f = unbox<unit -> AsyncReturn> o
this.ExecuteWithTrampoline f |> ignore)
| _ -> ()
threadStartCallbackForStartThreadWithTrampoline
/// Execute an async computation after installing a trampoline on its synchronous stack.
[<DebuggerHidden>]
member _.ExecuteWithTrampoline firstAction =
trampoline <- Trampoline()
trampoline.Execute firstAction
member this.PostWithTrampoline (syncCtxt: SynchronizationContext) (f: unit -> AsyncReturn) =
syncCtxt.Post(getSendOrPostCallbackWithTrampoline (this), state = (f |> box))
AsyncReturn.Fake()
member this.QueueWorkItemWithTrampoline(f: unit -> AsyncReturn) =
if not (ThreadPool.QueueUserWorkItem(getWaitCallbackForQueueWorkItemWithTrampoline (this), f |> box)) then
failwith "failed to queue user work item"
AsyncReturn.Fake()
member this.PostOrQueueWithTrampoline (syncCtxt: SynchronizationContext) f =
match syncCtxt with
| null -> this.QueueWorkItemWithTrampoline f
| _ -> this.PostWithTrampoline syncCtxt f
// This should be the only call to Thread.Start in this library. We must always install a trampoline.
member this.StartThreadWithTrampoline(f: unit -> AsyncReturn) =
Thread(getThreadStartCallbackForStartThreadWithTrampoline (this), IsBackground = true)
.Start(f |> box)
AsyncReturn.Fake()
/// Save the exception continuation during propagation of an exception, or prior to raising an exception
member inline _.OnExceptionRaised econt =
trampoline.OnExceptionRaised econt
/// Call a continuation, but first check if an async computation should trampoline on its synchronous stack.
member inline _.HijackCheckThenCall (cont: 'T -> AsyncReturn) res =
if trampoline.IncrementBindCount() then
trampoline.Set(fun () -> cont res)
else
// NOTE: this must be a tailcall
cont res
/// Represents rarely changing components of an in-flight async computation
[<NoEquality; NoComparison>]
[<AutoSerializable(false)>]
type AsyncActivationAux =
{
/// The active cancellation token
token: CancellationToken
/// The exception continuation
econt: econt
/// The cancellation continuation
ccont: ccont
/// Holds some commonly-allocated callbacks and a mutable location to use for a trampoline
trampolineHolder: TrampolineHolder
}
/// Represents context for an in-flight async computation
[<NoEquality; NoComparison>]
[<AutoSerializable(false)>]
type AsyncActivationContents<'T> =
{
/// The success continuation
cont: cont<'T>
/// The rarely changing components
aux: AsyncActivationAux
}
/// A struct wrapper around AsyncActivationContents. Using a struct wrapper allows us to change representation of the
/// contents at a later point, e.g. to change the contents to a .NET Task or some other representation.
[<Struct; NoEquality; NoComparison>]
type AsyncActivation<'T>(contents: AsyncActivationContents<'T>) =
/// Produce a new execution context for a composite async
member ctxt.WithCancellationContinuation ccont =
AsyncActivation<'T>
{ contents with
aux = { ctxt.aux with ccont = ccont }
}
/// Produce a new execution context for a composite async
member ctxt.WithExceptionContinuation econt =
AsyncActivation<'T>
{ contents with
aux = { ctxt.aux with econt = econt }
}
/// Produce a new execution context for a composite async
member _.WithContinuation cont =
AsyncActivation<'U> { cont = cont; aux = contents.aux }
/// Produce a new execution context for a composite async
member _.WithContinuations(cont, econt) =
AsyncActivation<'U>
{
cont = cont
aux = { contents.aux with econt = econt }
}
/// Produce a new execution context for a composite async
member ctxt.WithContinuations(cont, econt, ccont) =
AsyncActivation<'T>
{
cont = cont
aux =
{ ctxt.aux with
econt = econt
ccont = ccont
}
}
/// The extra information relevant to the execution of the async
member _.aux = contents.aux
/// The success continuation relevant to the execution of the async
member _.cont = contents.cont
/// The exception continuation relevant to the execution of the async
member _.econt = contents.aux.econt
/// The cancellation continuation relevant to the execution of the async
member _.ccont = contents.aux.ccont
/// The cancellation token relevant to the execution of the async
member _.token = contents.aux.token
/// The trampoline holder being used to protect execution of the async
member _.trampolineHolder = contents.aux.trampolineHolder
/// Check if cancellation has been requested
member _.IsCancellationRequested = contents.aux.token.IsCancellationRequested
/// Call the cancellation continuation of the active computation
member _.OnCancellation() =
contents.aux.ccont (OperationCanceledException(contents.aux.token))
/// Check for trampoline hijacking.
//
// Note, this must make tailcalls, so may not be an instance member taking a byref argument,
// nor call any members taking byref arguments.
static member inline HijackCheckThenCall (ctxt: AsyncActivation<'T>) cont arg =
ctxt.aux.trampolineHolder.HijackCheckThenCall cont arg
/// Call the success continuation of the asynchronous execution context after checking for
/// cancellation and trampoline hijacking.
// - Cancellation check
// - Hijack check
//
// Note, this must make tailcalls, so may not be an instance member taking a byref argument.
static member Success (ctxt: AsyncActivation<'T>) result =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
AsyncActivation<'T>.HijackCheckThenCall ctxt ctxt.cont result
// For backwards API Compat
[<Obsolete("Call Success instead")>]
member ctxt.OnSuccess(result: 'T) =
AsyncActivation<'T>.Success ctxt result
/// Save the exception continuation during propagation of an exception, or prior to raising an exception
member _.OnExceptionRaised() =
contents.aux.trampolineHolder.OnExceptionRaised contents.aux.econt
/// Make an initial async activation.
static member Create cancellationToken trampolineHolder cont econt ccont : AsyncActivation<'T> =
AsyncActivation
{
cont = cont
aux =
{
token = cancellationToken
econt = econt
ccont = ccont
trampolineHolder = trampolineHolder
}
}
/// Queue the success continuation of the asynchronous execution context as a work item in the thread pool
/// after installing a trampoline
member ctxt.QueueContinuationWithTrampoline(result: 'T) =
let cont = ctxt.cont
ctxt.aux.trampolineHolder.QueueWorkItemWithTrampoline(fun () -> cont result)
/// Ensure that any exceptions raised by the immediate execution of "userCode"
/// are sent to the exception continuation. This is done by allowing the exception to propagate
/// to the trampoline, and the saved exception continuation is called there.
///
/// It is also valid for MakeAsync primitive code to call the exception continuation directly.
[<DebuggerHidden>]
member ctxt.ProtectCode userCode =
let mutable ok = false
try
let res = userCode ()
ok <- true
res
finally
if not ok then
ctxt.OnExceptionRaised()
member ctxt.PostWithTrampoline (syncCtxt: SynchronizationContext) (f: unit -> AsyncReturn) =
let holder = contents.aux.trampolineHolder
ctxt.ProtectCode(fun () -> holder.PostWithTrampoline syncCtxt f)
/// Call the success continuation of the asynchronous execution context
member ctxt.CallContinuation(result: 'T) =
ctxt.cont result
/// Represents an asynchronous computation
[<NoEquality; NoComparison; CompiledName("FSharpAsync`1")>]
type Async<'T> =
{
Invoke: (AsyncActivation<'T> -> AsyncReturn)
}
/// Mutable register to help ensure that code is only executed once
[<Sealed>]
type Latch() =
let mutable i = 0
/// Execute the latch
member _.Enter() =
Interlocked.CompareExchange(&i, 1, 0) = 0
/// Represents the result of an asynchronous computation
[<NoEquality; NoComparison>]
type AsyncResult<'T> =
| Ok of 'T
| Error of ExceptionDispatchInfo
| Canceled of OperationCanceledException
/// Get the result of an asynchronous computation
[<DebuggerHidden>]
member res.Commit() =
match res with
| AsyncResult.Ok res -> res
| AsyncResult.Error edi -> edi.ThrowAny()
| AsyncResult.Canceled exn -> raise exn
/// Primitives to execute asynchronous computations
module AsyncPrimitives =
let inline fake () =
Unchecked.defaultof<AsyncReturn>
let inline unfake (_: AsyncReturn) =
()
/// The mutable global CancellationTokenSource, see Async.DefaultCancellationToken
let mutable defaultCancellationTokenSource = new CancellationTokenSource()
/// Primitive to invoke an async computation.
//
// Note: direct calls to this function may end up in user assemblies via inlining
[<DebuggerHidden>]
let Invoke (computation: Async<'T>) (ctxt: AsyncActivation<_>) : AsyncReturn =
AsyncActivation<'T>.HijackCheckThenCall ctxt computation.Invoke ctxt
/// Apply 'userCode' to 'arg'. If no exception is raised then call the normal continuation. Used to implement
/// 'finally' and 'when cancelled'.
///
/// - Apply 'userCode' to argument with exception protection
/// - Hijack check before invoking the continuation
[<DebuggerHidden>]
let CallThenContinue userCode arg (ctxt: AsyncActivation<_>) : AsyncReturn =
let mutable result = Unchecked.defaultof<_>
let mutable ok = false
try
result <- userCode arg
ok <- true
finally
if not ok then
ctxt.OnExceptionRaised()
if ok then
AsyncActivation<'T>.HijackCheckThenCall ctxt ctxt.cont result
else
fake ()
/// Apply 'part2' to 'result1' and invoke the resulting computation.
///
/// Note: direct calls to this function end up in user assemblies via inlining
///
/// - Apply 'part2' to argument with exception protection
/// - Hijack check before invoking the resulting computation
[<DebuggerHidden>]
let CallThenInvoke (ctxt: AsyncActivation<_>) result1 part2 : AsyncReturn =
let mutable result = Unchecked.defaultof<_>
let mutable ok = false
try
result <- part2 result1
ok <- true
finally
if not ok then
ctxt.OnExceptionRaised()
if ok then
Invoke result ctxt
else
fake ()
/// Like `CallThenInvoke` but does not do a hijack check for historical reasons (exact code compat)
[<DebuggerHidden>]
let CallThenInvokeNoHijackCheck (ctxt: AsyncActivation<_>) result1 userCode =
let mutable res = Unchecked.defaultof<_>
let mutable ok = false
try
res <- userCode result1
ok <- true
finally
if not ok then
ctxt.OnExceptionRaised()
if ok then res.Invoke ctxt else fake ()
/// Apply 'filterFunction' to 'arg'. If the result is 'Some' invoke the resulting computation. If the result is 'None'
/// then send 'result1' to the exception continuation.
///
/// - Apply 'filterFunction' to argument with exception protection
/// - Hijack check before invoking the resulting computation or exception continuation
[<DebuggerHidden>]
let CallFilterThenInvoke (ctxt: AsyncActivation<'T>) filterFunction (edi: ExceptionDispatchInfo) : AsyncReturn =
let mutable resOpt = None
let mutable ok = false
try
resOpt <- filterFunction (edi.GetAssociatedSourceException())
ok <- true
finally
if not ok then
ctxt.OnExceptionRaised()
if ok then
match resOpt with
| None -> AsyncActivation<'T>.HijackCheckThenCall ctxt ctxt.econt edi
| Some res -> Invoke res ctxt
else
fake ()
/// Build a primitive without any exception or resync protection
[<DebuggerHidden>]
let MakeAsync body =
{ Invoke = body }
[<DebuggerHidden>]
let MakeAsyncWithCancelCheck body =
MakeAsync(fun ctxt ->
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
body ctxt)
/// Execute part1, then apply part2, then execute the result of that
///
/// Note: direct calls to this function end up in user assemblies via inlining
/// - Initial cancellation check
/// - Initial hijack check (see Invoke)
/// - No hijack check after applying 'part2' to argument (see CallThenInvoke)
/// - No cancellation check after applying 'part2' to argument (see CallThenInvoke)
/// - Apply 'part2' to argument with exception protection (see CallThenInvoke)
[<DebuggerHidden>]
let Bind (ctxt: AsyncActivation<'T>) (part1: Async<'U>) (part2: 'U -> Async<'T>) : AsyncReturn =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
// Note, no cancellation check is done before calling 'part2'. This is
// because part1 may bind a resource, while part2 is a try/finally, and, if
// the resource creation completes, we want to enter part2 before cancellation takes effect.
Invoke part1 (ctxt.WithContinuation(fun result1 -> CallThenInvokeNoHijackCheck ctxt result1 part2))
/// Re-route all continuations to execute the finally function.
/// - Cancellation check after 'entering' the try/finally and before running the body
/// - Hijack check after 'entering' the try/finally and before running the body (see Invoke)
/// - Run 'finallyFunction' with exception protection (see CallThenContinue)
/// - Hijack check before any of the continuations (see CallThenContinue)
[<DebuggerHidden>]
let TryFinally (ctxt: AsyncActivation<'T>) (computation: Async<'T>) finallyFunction =
// Note, we don't test for cancellation before entering a try/finally. This prevents
// a resource being created without being disposed.
// The new continuation runs the finallyFunction and resumes the old continuation
// If an exception is thrown we continue with the previous exception continuation.
let cont result =
CallThenContinue finallyFunction () (ctxt.WithContinuation(fun () -> ctxt.cont result))
// The new exception continuation runs the finallyFunction and then runs the previous exception continuation.
// If an exception is thrown we continue with the previous exception continuation.
let econt edi =
CallThenContinue finallyFunction () (ctxt.WithContinuation(fun () -> ctxt.econt edi))
// The cancellation continuation runs the finallyFunction and then runs the previous cancellation continuation.
// If an exception is thrown we continue with the previous cancellation continuation (the exception is lost)
let ccont cexn =
CallThenContinue
finallyFunction
()
(ctxt.WithContinuations(cont = (fun () -> ctxt.ccont cexn), econt = (fun _ -> ctxt.ccont cexn)))
let ctxt = ctxt.WithContinuations(cont = cont, econt = econt, ccont = ccont)
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
computation.Invoke ctxt
/// Re-route the exception continuation to call to catchFunction. If catchFunction returns None then call the exception continuation.
/// If it returns Some, invoke the resulting async.
/// - Cancellation check before entering the try
/// - No hijack check after 'entering' the try/with
/// - Cancellation check before applying the 'catchFunction'
/// - Apply `catchFunction' to argument with exception protection (see CallFilterThenInvoke)
/// - Hijack check before invoking the resulting computation or exception continuation (see CallFilterThenInvoke)
[<DebuggerHidden>]
let TryWith (ctxt: AsyncActivation<'T>) (computation: Async<'T>) catchFunction =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
let ctxt =
ctxt.WithExceptionContinuation(fun edi ->
if ctxt.IsCancellationRequested then
ctxt.OnCancellation()
else
CallFilterThenInvoke ctxt catchFunction edi)
computation.Invoke ctxt
/// Make an async for an AsyncResult
// - No cancellation check
// - No hijack check
let CreateAsyncResultAsync res =
MakeAsync(fun ctxt ->
match res with
| AsyncResult.Ok r -> ctxt.cont r
| AsyncResult.Error edi -> ctxt.econt edi
| AsyncResult.Canceled cexn -> ctxt.ccont cexn)
/// Generate async computation which calls its continuation with the given result
/// - Cancellation check (see OnSuccess)
/// - Hijack check (see OnSuccess)
let inline CreateReturnAsync res =
// Note: this code ends up in user assemblies via inlining
MakeAsync(fun ctxt -> AsyncActivation.Success ctxt res)
/// Runs the first process, takes its result, applies f and then runs the new process produced.
/// - Initial cancellation check (see Bind)
/// - Initial hijack check (see Bind)
/// - No hijack check after applying 'part2' to argument (see Bind)
/// - No cancellation check after applying 'part2' to argument (see Bind)
/// - Apply 'part2' to argument with exception protection (see Bind)
let inline CreateBindAsync part1 part2 =
// Note: this code ends up in user assemblies via inlining
MakeAsync(fun ctxt -> Bind ctxt part1 part2)
/// Call the given function with exception protection.
/// - No initial cancellation check
/// - Hijack check after applying part2 to argument (see CallThenInvoke)
let inline CreateCallAsync part2 result1 =
// Note: this code ends up in user assemblies via inlining
MakeAsync(fun ctxt -> CallThenInvoke ctxt result1 part2)
/// Call the given function with exception protection.
/// - Initial cancellation check
/// - Hijack check after applying computation to argument (see CallThenInvoke)
/// - Apply 'computation' to argument with exception protection (see CallThenInvoke)
let inline CreateDelayAsync computation =
// Note: this code ends up in user assemblies via inlining
MakeAsyncWithCancelCheck(fun ctxt -> CallThenInvoke ctxt () computation)
/// Implements the sequencing construct of async computation expressions
/// - Initial cancellation check (see CreateBindAsync)
/// - Initial hijack check (see CreateBindAsync)
/// - No hijack check after applying 'part2' to argument (see CreateBindAsync)
/// - No cancellation check after applying 'part2' to argument (see CreateBindAsync)
/// - Apply 'part2' to argument with exception protection (see CreateBindAsync)
let inline CreateSequentialAsync part1 part2 =
// Note: this code ends up in user assemblies via inlining
CreateBindAsync part1 (fun () -> part2)
/// Create an async for a try/finally
/// - Cancellation check after 'entering' the try/finally and before running the body
/// - Hijack check after 'entering' the try/finally and before running the body (see TryFinally)
/// - Apply 'finallyFunction' with exception protection (see TryFinally)
let inline CreateTryFinallyAsync finallyFunction computation =
MakeAsync(fun ctxt -> TryFinally ctxt computation finallyFunction)
/// Create an async for a try/with filtering exceptions through a pattern match
/// - Cancellation check before entering the try (see TryWith)
/// - Cancellation check before entering the with (see TryWith)
/// - Apply `filterFunction' to argument with exception protection (see TryWith)
/// - Hijack check before invoking the resulting computation or exception continuation
let inline CreateTryWithFilterAsync filterFunction computation =
MakeAsync(fun ctxt -> TryWith ctxt computation filterFunction)
/// Create an async for a try/with filtering
/// - Cancellation check before entering the try (see TryWith)
/// - Cancellation check before entering the with (see TryWith)
/// - Apply `catchFunction' to argument with exception protection (see TryWith)
/// - Hijack check before invoking the resulting computation or exception continuation
let inline CreateTryWithAsync catchFunction computation =
MakeAsync(fun ctxt -> TryWith ctxt computation (catchFunction >> Some))
/// Call the finallyFunction if the computation results in a cancellation, and then continue with cancellation.
/// If the finally function gives an exception then continue with cancellation regardless.
/// - No cancellation check before entering the when-cancelled
/// - No hijack check before entering the when-cancelled
/// - Apply `finallyFunction' to argument with exception protection (see CallThenContinue)
/// - Hijack check before continuing with cancellation (see CallThenContinue)
let CreateWhenCancelledAsync (finallyFunction: OperationCanceledException -> unit) computation =
MakeAsync(fun ctxt ->
let ccont = ctxt.ccont
let ctxt =
ctxt.WithCancellationContinuation(fun cexn ->
CallThenContinue
finallyFunction
cexn
(ctxt.WithContinuations(cont = (fun _ -> ccont cexn), econt = (fun _ -> ccont cexn))))
computation.Invoke ctxt)
/// A single pre-allocated computation that fetched the current cancellation token
let cancellationTokenAsync = MakeAsync(fun ctxt -> ctxt.cont ctxt.aux.token)
/// A single pre-allocated computation that returns a unit result
/// - Cancellation check (see CreateReturnAsync)
/// - Hijack check (see CreateReturnAsync)
let unitAsync = CreateReturnAsync()
/// Implement use/Dispose
///
/// - No initial cancellation check before applying computation to its argument. See CreateTryFinallyAsync
/// and CreateCallAsync. We enter the try/finally before any cancel checks.
/// - Cancellation check after 'entering' the implied try/finally and before running the body (see CreateTryFinallyAsync)
/// - Hijack check after 'entering' the implied try/finally and before running the body (see CreateTryFinallyAsync)
/// - Run 'disposeFunction' with exception protection (see CreateTryFinallyAsync)
let CreateUsingAsync (resource: 'T :> IDisposable) (computation: 'T -> Async<'a>) : Async<'a> =
let disposeFunction () =
Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.Dispose resource
CreateTryFinallyAsync disposeFunction (CreateCallAsync computation resource)
/// - Initial cancellation check (see CreateBindAsync)
/// - Initial hijack check (see CreateBindAsync)
/// - Cancellation check after (see unitAsync)
/// - No hijack check after (see unitAsync)
let inline CreateIgnoreAsync computation =
CreateBindAsync computation (fun _ -> unitAsync)
/// Implement the while loop construct of async computation expressions
/// - No initial cancellation check before first execution of guard
/// - No initial hijack check before first execution of guard
/// - No cancellation check before each execution of guard (see CreateBindAsync)
/// - Hijack check before each execution of guard (see CreateBindAsync)
/// - Cancellation check before each execution of the body after guard (CreateBindAsync)
/// - No hijack check before each execution of the body after guard (see CreateBindAsync)
/// - Cancellation check after guard fails (see unitAsync)
/// - Hijack check after guard fails (see unitAsync)
/// - Apply 'guardFunc' with exception protection (see ProtectCode)
//
// Note: There are allocations during loop set up, but no allocations during iterations of the loop
let CreateWhileAsync guardFunc computation =
if guardFunc () then
let mutable whileAsync = Unchecked.defaultof<_>
whileAsync <-
CreateBindAsync computation (fun () ->
if guardFunc () then
whileAsync
else
unitAsync)
whileAsync
else
unitAsync
#if REDUCED_ALLOCATIONS_BUT_RUNS_SLOWER
/// Implement the while loop construct of async computation expressions
/// - Initial cancellation check before each execution of guard
/// - No initial hijack check before each execution of guard
/// - No cancellation check before each execution of the body after guard
/// - Hijack check before each execution of the body after guard (see Invoke)
/// - Cancellation check after guard fails (see OnSuccess)
/// - Hijack check after guard fails (see OnSuccess)
/// - Apply 'guardFunc' with exception protection (see ProtectCode)
//
// Note: There are allocations during loop set up, but no allocations during iterations of the loop
// One allocation for While async
// One allocation for While async context function
MakeAsync(fun ctxtGuard ->
// One allocation for ctxtLoop reference cell
let mutable ctxtLoop = Unchecked.defaultof<_>
// One allocation for While recursive closure
let rec WhileLoop () =
if ctxtGuard.IsCancellationRequested then
ctxtGuard.OnCancellation()
elif ctxtGuard.ProtectCode guardFunc then
Invoke computation ctxtLoop
else
ctxtGuard.OnSuccess()
// One allocation for While body activation context
ctxtLoop <- ctxtGuard.WithContinuation(WhileLoop)
WhileLoop())
#endif
/// Implement the for loop construct of async computation expressions
/// - No initial cancellation check before GetEnumerator call.
/// - No initial cancellation check before entering protection of implied try/finally
/// - Cancellation check after 'entering' the implied try/finally and before loop
/// - Hijack check after 'entering' the implied try/finally and after MoveNext call
/// - Do not apply 'GetEnumerator' with exception protection. However for an 'async'
/// in an 'async { ... }' the exception protection will be provided by the enclosing
/// Delay or Bind or similar construct.
/// - Apply 'MoveNext' with exception protection
/// - Apply 'Current' with exception protection
// Note: No allocations during iterations of the loop apart from those from
// applying the loop body to the element
let CreateForLoopAsync (source: seq<_>) computation =
CreateUsingAsync (source.GetEnumerator()) (fun ie ->
CreateWhileAsync (fun () -> ie.MoveNext()) (CreateDelayAsync(fun () -> computation ie.Current)))
#if REDUCED_ALLOCATIONS_BUT_RUNS_SLOWER
CreateUsingAsync (source.GetEnumerator()) (fun ie ->
// One allocation for While async
// One allocation for While async context function
MakeAsync(fun ctxtGuard ->
// One allocation for ctxtLoop reference cell
let mutable ctxtLoop = Unchecked.defaultof<_>
// Two allocations for protected functions
let guardFunc () =
ie.MoveNext()
let currentFunc () =
ie.Current
// One allocation for ForLoop recursive closure
let rec ForLoop () =
if ctxtGuard.IsCancellationRequested then
ctxtGuard.OnCancellation()
elif ctxtGuard.ProtectCode guardFunc then
let x = ctxtGuard.ProtectCode currentFunc
CallThenInvoke ctxtLoop x computation
else
ctxtGuard.OnSuccess()
// One allocation for loop activation context
ctxtLoop <- ctxtGuard.WithContinuation(ForLoop)
ForLoop()))
#endif
/// - Initial cancellation check
/// - Call syncCtxt.Post with exception protection. This may fail as it is arbitrary user code
#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT
let CreateSwitchToAsync (syncCtxt: SynchronizationContext) =
#else
let CreateSwitchToAsync (syncCtxt: SynchronizationContext | null) =
#endif
MakeAsyncWithCancelCheck(fun ctxt -> ctxt.PostWithTrampoline syncCtxt ctxt.cont)
/// - Initial cancellation check
/// - Create Thread and call Start() with exception protection. We don't expect this
/// to fail but protect nevertheless.
let CreateSwitchToNewThreadAsync () =
MakeAsyncWithCancelCheck(fun ctxt ->
ctxt.ProtectCode(fun () -> ctxt.trampolineHolder.StartThreadWithTrampoline ctxt.cont))
/// - Initial cancellation check
/// - Call ThreadPool.QueueUserWorkItem with exception protection. We don't expect this
/// to fail but protect nevertheless.
let CreateSwitchToThreadPoolAsync () =
MakeAsyncWithCancelCheck(fun ctxt ->
ctxt.ProtectCode(fun () -> ctxt.trampolineHolder.QueueWorkItemWithTrampoline ctxt.cont))
/// Post back to the sync context regardless of which continuation is taken
/// - Call syncCtxt.Post with exception protection
let DelimitSyncContext (ctxt: AsyncActivation<_>) =
match SynchronizationContext.Current with
| null -> ctxt
| syncCtxt ->
ctxt.WithContinuations(
cont = (fun x -> ctxt.PostWithTrampoline syncCtxt (fun () -> ctxt.cont x)),
econt = (fun edi -> ctxt.PostWithTrampoline syncCtxt (fun () -> ctxt.econt edi)),
ccont = (fun cexn -> ctxt.PostWithTrampoline syncCtxt (fun () -> ctxt.ccont cexn))
)
[<Sealed>]
[<AutoSerializable(false)>]
type SuspendedAsync<'T>(ctxt: AsyncActivation<'T>) =
let syncCtxt = SynchronizationContext.Current
let thread =
match syncCtxt with
| null -> null // saving a thread-local access
| _ -> Thread.CurrentThread
let trampolineHolder = ctxt.trampolineHolder
member _.ContinueImmediate res =
let action () =
ctxt.cont res
let inline executeImmediately () =
trampolineHolder.ExecuteWithTrampoline action
let currentSyncCtxt = SynchronizationContext.Current
match syncCtxt, currentSyncCtxt with
| null, null -> executeImmediately ()
// This logic was added in F# 2.0 though is incorrect from the perspective of
// how SynchronizationContext is meant to work. However the logic works for
// mainline scenarios (WinForms/WPF) and for compatibility reasons we won't change it.
| _ when Object.Equals(syncCtxt, currentSyncCtxt) && thread.Equals Thread.CurrentThread ->
executeImmediately ()
| _ -> trampolineHolder.PostOrQueueWithTrampoline syncCtxt action
member _.PostOrQueueWithTrampoline res =
trampolineHolder.PostOrQueueWithTrampoline syncCtxt (fun () -> ctxt.cont res)
/// A utility type to provide a synchronization point between an asynchronous computation
/// and callers waiting on the result of that computation.
///
/// Use with care!
[<Sealed>]
[<AutoSerializable(false)>]
type ResultCell<'T>() =
let mutable result = None
// The continuations for the result
let mutable savedConts: SuspendedAsync<'T> list = []
// The WaitHandle event for the result. Only created if needed, and set to null when disposed.
let mutable resEvent = null
let mutable disposed = false
// All writers of result are protected by lock on syncRoot.
let syncRoot = obj ()
member x.GetWaitHandle() =
lock syncRoot (fun () ->
if disposed then
raise (System.ObjectDisposedException("ResultCell"))
match resEvent with
| null ->
// Start in signalled state if a result is already present.
let ev = new ManualResetEvent(result.IsSome)
resEvent <- ev
(ev :> WaitHandle)
| ev -> (ev :> WaitHandle))
member x.Close() =
lock syncRoot (fun () ->
if not disposed then
disposed <- true
match resEvent with
| null -> ()
| ev ->
ev.Close()
resEvent <- null)
interface IDisposable with
member x.Dispose() =
x.Close()
member x.GrabResult() =
match result with
| Some res -> res
| None -> failwith "Unexpected no result"
/// Record the result in the ResultCell.
member x.RegisterResult(res: 'T, reuseThread) =
let grabbedConts =
lock syncRoot (fun () ->
// Ignore multiple sets of the result. This can happen, e.g. for a race between a cancellation and a success
if x.ResultAvailable then
[] // invalidOp "multiple results registered for asynchronous operation"
else if
// In this case the ResultCell has already been disposed, e.g. due to a timeout.