forked from dotnet/fsharp
/
async.fs
1817 lines (1521 loc) · 90.2 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 this.Token = linkedCTS.Token
member this.Cancel() = failureCTS.Cancel()
member this.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
type cont<'T> = ('T -> AsyncReturn)
type econt = (ExceptionDispatchInfo -> AsyncReturn)
type ccont = (OperationCanceledException -> AsyncReturn)
[<AllowNullLiteral>]
type Trampoline() =
let fake () = Unchecked.defaultof<AsyncReturn>
let unfake (_ : AsyncReturn) = ()
[<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 thisIsTopTrampoline =
if Trampoline.thisThreadHasTrampoline then
false
else
Trampoline.thisThreadHasTrampoline <- true
true
try
let mutable keepGoing = true
let mutable action = firstAction
while keepGoing do
try
action() |> unfake
match storedCont with
| None ->
keepGoing <- false
| Some cont ->
storedCont <- None
action <- cont
// Let the exception propagate all the way to the trampoline to get a full .StackTrace entry
with exn ->
match storedExnCont with
| None ->
reraise()
| Some econt ->
storedExnCont <- None
let edi = ExceptionDispatchInfo.RestoreOrCapture exn
action <- (fun () -> econt edi)
finally
if thisIsTopTrampoline then
Trampoline.thisThreadHasTrampoline <- false
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
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() as this =
let mutable trampoline = null
let fake () = Unchecked.defaultof<AsyncReturn>
static let unfake (_: AsyncReturn) = ()
// Preallocate this delegate and keep it in the trampoline holder.
let sendOrPostCallbackWithTrampoline =
SendOrPostCallback (fun o ->
let f = unbox<(unit -> AsyncReturn)> o
this.ExecuteWithTrampoline f |> unfake)
// Preallocate this delegate and keep it in the trampoline holder.
let waitCallbackForQueueWorkItemWithTrampoline =
WaitCallback (fun o ->
let f = unbox<(unit -> AsyncReturn)> o
this.ExecuteWithTrampoline f |> unfake)
// Preallocate this delegate and keep it in the trampoline holder.
let threadStartCallbackForStartThreadWithTrampoline =
ParameterizedThreadStart (fun o ->
let f = unbox<(unit -> AsyncReturn)> o
this.ExecuteWithTrampoline f |> unfake)
/// Execute an async computation after installing a trampoline on its synchronous stack.
[<DebuggerHidden>]
member __.ExecuteWithTrampoline firstAction =
trampoline <- new Trampoline()
trampoline.Execute firstAction
member this.PostWithTrampoline (syncCtxt: SynchronizationContext) (f: unit -> AsyncReturn) =
syncCtxt.Post (sendOrPostCallbackWithTrampoline, state=(f |> box))
fake()
member this.QueueWorkItemWithTrampoline (f: unit -> AsyncReturn) =
if not (ThreadPool.QueueUserWorkItem(waitCallbackForQueueWorkItemWithTrampoline, f |> box)) then
failwith "failed to queue user work item"
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 __.StartThreadWithTrampoline (f: unit -> AsyncReturn) =
(new Thread(threadStartCallbackForStartThreadWithTrampoline, IsBackground=true)).Start(f|>box)
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
[<NoEquality; NoComparison>]
[<AutoSerializable(false)>]
/// Represents rarely changing components of an in-flight async computation
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 }
[<NoEquality; NoComparison>]
[<AutoSerializable(false)>]
/// Represents context for an in-flight async computation
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 ctxt.WithContinuation cont = AsyncActivation<'U> { cont = cont; aux = contents.aux }
/// Produce a new execution context for a composite async
member ctxt.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> { contents with cont = cont; aux = { ctxt.aux with econt = econt; ccont = ccont } }
/// The extra information relevant to the execution of the async
member ctxt.aux = contents.aux
/// The success continuation relevant to the execution of the async
member ctxt.cont = contents.cont
/// The exception continuation relevant to the execution of the async
member ctxt.econt = contents.aux.econt
/// The cancellation continuation relevant to the execution of the async
member ctxt.ccont = contents.aux.ccont
/// The cancellation token relevant to the execution of the async
member ctxt.token = contents.aux.token
/// The trampoline holder being used to protect execution of the async
member ctxt.trampolineHolder = contents.aux.trampolineHolder
/// Check if cancellation has been requested
member ctxt.IsCancellationRequested = contents.aux.token.IsCancellationRequested
/// Call the cancellation continuation of the active computation
member ctxt.OnCancellation () =
contents.aux.ccont (new OperationCanceledException (contents.aux.token))
/// Check for trampoline hijacking.
member inline ctxt.HijackCheckThenCall cont arg =
contents.aux.trampolineHolder.HijackCheckThenCall cont arg
/// Call the success continuation of the asynchronous execution context after checking for
/// cancellation and trampoline hijacking.
member ctxt.OnSuccess result =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
ctxt.HijackCheckThenCall ctxt.cont result
/// Call the exception continuation directly
member ctxt.CallExceptionContinuation edi =
contents.aux.econt edi
/// Save the exception continuation during propagation of an exception, or prior to raising an exception
member ctxt.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 ctxt = ctxt
ctxt.aux.trampolineHolder.QueueWorkItemWithTrampoline(fun () -> ctxt.cont result)
/// 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 this.Enter() = Interlocked.CompareExchange(&i, 1, 0) = 0
/// Ensures that a function is only called once
[<Sealed>]
type Once() =
let latch = Latch()
/// Execute the function at most once
member this.Do f =
if latch.Enter() then
f()
/// 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 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 =
ctxt.HijackCheckThenCall computation.Invoke ctxt
/// Apply userCode to x. If no exception is raised then call the normal continuation. Used to implement
/// 'finally' and 'when cancelled'.
[<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
ctxt.HijackCheckThenCall 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
[<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<_>) userCode result1 =
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 'catchFilter' to 'arg'. If the result is 'Some' invoke the resulting computation. If the result is 'None'
/// then send 'result1' to the exception continuation.
[<DebuggerHidden>]
let CallFilterThenInvoke (ctxt: AsyncActivation<'T>) catchFilter (edi: ExceptionDispatchInfo) : AsyncReturn =
let mutable resOpt = Unchecked.defaultof<_>
let mutable ok = false
try
resOpt <- catchFilter (edi.GetAssociatedSourceException())
ok <- true
finally
if not ok then
ctxt.OnExceptionRaised()
if ok then
match resOpt with
| None ->
ctxt.HijackCheckThenCall ctxt.econt edi
| Some res ->
Invoke res ctxt
else
fake()
/// Internal way of making an async from code, for exact code compat.
/// Perform a cancellation check and ensure that any exceptions raised by
/// the immediate execution of "userCode" are sent to the exception continuation.
[<DebuggerHidden>]
let ProtectedCode (ctxt: AsyncActivation<'T>) userCode =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
let mutable ok = false
try
let res = userCode ctxt
ok <- true
res
finally
if not ok then
ctxt.OnExceptionRaised()
/// Build a primitive without any exception or resync protection
[<DebuggerHidden>]
let MakeAsync body = { Invoke = body }
[<DebuggerHidden>]
// Note: direct calls to this function end up in user assemblies via inlining
let Bind (ctxt: AsyncActivation<'T>) (part1: Async<'U>) (part2: 'U -> Async<'T>) : AsyncReturn =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
Invoke part1 (ctxt.WithContinuation(fun result1 -> CallThenInvokeNoHijackCheck ctxt part2 result1 ))
[<DebuggerHidden>]
/// Re-route all continuations to execute the finally function.
let TryFinally (ctxt: AsyncActivation<'T>) computation finallyFunction =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
// 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 exn =
CallThenContinue finallyFunction () (ctxt.WithContinuation(fun () -> ctxt.econt exn))
// 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 newCtxt = ctxt.WithContinuations(cont=cont, econt=econt, ccont=ccont)
computation.Invoke newCtxt
/// 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.
[<DebuggerHidden>]
let TryWith (ctxt: AsyncActivation<'T>) computation catchFunction =
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
let newCtxt =
ctxt.WithExceptionContinuation(fun edi ->
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
CallFilterThenInvoke ctxt catchFunction edi)
computation.Invoke newCtxt
/// Internal way of making an async from code, for exact code compat.
/// When run, ensures that any exceptions raised by the immediate execution of "f" are
/// sent to the exception continuation.
let CreateProtectedAsync f =
MakeAsync (fun ctxt -> ProtectedCode ctxt f)
/// Internal way of making an async from result, for exact code compat.
let CreateAsyncResultAsync res =
MakeAsync (fun ctxt ->
match res with
| AsyncResult.Ok r -> ctxt.cont r
| AsyncResult.Error edi -> ctxt.CallExceptionContinuation edi
| AsyncResult.Canceled oce -> ctxt.ccont oce)
// Generate async computation which calls its continuation with the given result
let inline CreateReturnAsync res =
// Note: this code ends up in user assemblies via inlining
MakeAsync (fun ctxt -> ctxt.OnSuccess res)
// The primitive bind operation. Generate a process that runs the first process, takes
// its result, applies f and then runs the new process produced. Hijack if necessary and
// run 'f' with exception protection
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, but first
// check for cancellation.
let inline CreateCallAsync part2 result1 =
// Note: this code ends up in user assemblies via inlining
MakeAsync (fun ctxt ->
if ctxt.IsCancellationRequested then
ctxt.OnCancellation ()
else
CallThenInvoke ctxt result1 part2)
let inline CreateDelayAsync computation =
// Note: this code ends up in user assemblies via inlining
CreateCallAsync computation ()
/// Implements the sequencing construct of async computation expressions
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
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
let inline CreateTryWithFilterAsync catchFunction computation =
MakeAsync (fun ctxt -> TryWith ctxt computation (fun edi -> catchFunction edi))
/// Create an async for a try/with filtering
let inline CreateTryWithAsync catchFunction computation =
CreateTryWithFilterAsync (fun exn -> Some (catchFunction exn)) computation
/// 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.
let CreateWhenCancelledAsync (finallyFunction: OperationCanceledException -> unit) computation =
MakeAsync (fun ctxt ->
let ccont = ctxt.ccont
let newCtxt =
ctxt.WithCancellationContinuation(fun exn ->
CallThenContinue finallyFunction exn (ctxt.WithContinuations(cont = (fun _ -> ccont exn), econt = (fun _ -> ccont exn))))
computation.Invoke newCtxt)
/// 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
let unitAsync =
CreateReturnAsync()
/// Implement use/Dispose
let CreateUsingAsync (resource:'T :> IDisposable) (computation:'T -> Async<'a>) : Async<'a> =
let mutable x = 0
let disposeFunction _ =
if Interlocked.CompareExchange(&x, 1, 0) = 0 then
Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.Dispose resource
CreateTryFinallyAsync disposeFunction (CreateCallAsync computation resource) |> CreateWhenCancelledAsync disposeFunction
let inline CreateIgnoreAsync computation =
CreateBindAsync computation (fun _ -> unitAsync)
/// Implement the while loop construct of async computation expressions
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
/// Implement the for loop construct of async commputation expressions
let CreateForLoopAsync (source: seq<_>) computation =
CreateUsingAsync (source.GetEnumerator()) (fun ie ->
CreateWhileAsync
(fun () -> ie.MoveNext())
(CreateDelayAsync (fun () -> computation ie.Current)))
let CreateSwitchToAsync (syncCtxt: SynchronizationContext) =
CreateProtectedAsync (fun ctxt ->
ctxt.trampolineHolder.PostWithTrampoline syncCtxt ctxt.cont)
let CreateSwitchToNewThreadAsync() =
CreateProtectedAsync (fun ctxt ->
ctxt.trampolineHolder.StartThreadWithTrampoline ctxt.cont)
let CreateSwitchToThreadPoolAsync() =
CreateProtectedAsync (fun ctxt ->
ctxt.trampolineHolder.QueueWorkItemWithTrampoline ctxt.cont)
/// Post back to the sync context regardless of which continuation is taken
let DelimitSyncContext (ctxt: AsyncActivation<_>) =
match SynchronizationContext.Current with
| null -> ctxt
| syncCtxt ->
ctxt.WithContinuations(cont = (fun x -> ctxt.trampolineHolder.PostWithTrampoline syncCtxt (fun () -> ctxt.cont x)),
econt = (fun x -> ctxt.trampolineHolder.PostWithTrampoline syncCtxt (fun () -> ctxt.econt x)),
ccont = (fun x -> ctxt.trampolineHolder.PostWithTrampoline syncCtxt (fun () -> ctxt.ccont x)))
// When run, ensures that each of the continuations of the process are run in the same synchronization context.
let CreateDelimitedUserCodeAsync f =
CreateProtectedAsync (fun ctxt ->
let ctxtWithSync = DelimitSyncContext ctxt
f ctxtWithSync)
[<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 ()
// See bug 370350; this logic is incorrect from the perspective of how SynchronizationContext is meant to work,
// but the logic works for mainline scenarios (WinForms/WPF/ASP.NET) and we won't change it again.
| _ when Object.Equals(syncCtxt, currentSyncCtxt) && thread.Equals Thread.CurrentThread ->
executeImmediately ()
| _ ->
trampolineHolder.PostOrQueueWithTrampoline syncCtxt action
member __.ContinueWithPostOrQueue 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: list<SuspendedAsync<'T>> = []
// 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 = new Object()
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
// In this case the ResultCell has already been disposed, e.g. due to a timeout.
// The result is dropped on the floor.
if disposed then
[]
else
result <- Some res
// If the resEvent exists then set it. If not we can skip setting it altogether and it won't be
// created
match resEvent with
| null ->
()
| ev ->
// Setting the event need to happen under lock so as not to race with Close()
ev.Set () |> ignore
List.rev savedConts)
// Run the action outside the lock
match grabbedConts with
| [] -> fake()
| [cont] ->
if reuseThread then
cont.ContinueImmediate res
else
cont.ContinueWithPostOrQueue res
| otherwise ->
otherwise |> List.iter (fun cont -> cont.ContinueWithPostOrQueue res |> unfake) |> fake
member x.ResultAvailable = result.IsSome
/// Await the result of a result cell, without a direct timeout or direct
/// cancellation. That is, the underlying computation must fill the result
/// if cancellation or timeout occurs.
member x.AwaitResult_NoDirectCancelOrTimeout =
MakeAsync (fun ctxt ->
// Check if a result is available synchronously
let resOpt =
match result with
| Some _ -> result
| None ->
lock syncRoot (fun () ->
match result with
| Some _ ->
result
| None ->
// Otherwise save the continuation and call it in RegisterResult
savedConts <- (SuspendedAsync<_>(ctxt)) :: savedConts
None
)
match resOpt with
| Some res -> ctxt.cont res
| None -> fake()
)
member x.TryWaitForResultSynchronously (?timeout) : 'T option =
// Check if a result is available.
match result with
| Some _ as r ->
r
| None ->
// Force the creation of the WaitHandle
let resHandle = x.GetWaitHandle()
// Check again. While we were in GetWaitHandle, a call to RegisterResult may have set result then skipped the
// Set because the resHandle wasn't forced.
match result with
| Some _ as r ->
r
| None ->
// OK, let's really wait for the Set signal. This may block.
let timeout = defaultArg timeout Threading.Timeout.Infinite
let ok = resHandle.WaitOne(millisecondsTimeout= timeout, exitContext=true)
if ok then
// Now the result really must be available
result
else
// timed out
None
/// Create an instance of an arbitrary delegate type delegating to the given F# function
type FuncDelegate<'T>(f) =
member __.Invoke(sender:obj, a:'T) : unit = ignore sender; f a
static member Create<'Delegate when 'Delegate :> Delegate>(f) =
let obj = FuncDelegate<'T>(f)
let invokeMeth = (typeof<FuncDelegate<'T>>).GetMethod("Invoke", BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance)
System.Delegate.CreateDelegate(typeof<'Delegate>, obj, invokeMeth) :?> 'Delegate
[<DebuggerHidden>]
let QueueAsync cancellationToken cont econt ccont computation =
let trampolineHolder = new TrampolineHolder()
trampolineHolder.QueueWorkItemWithTrampoline (fun () ->
let ctxt = AsyncActivation.Create cancellationToken trampolineHolder cont econt ccont
computation.Invoke ctxt)
/// Run the asynchronous workflow and wait for its result.
[<DebuggerHidden>]
let RunSynchronouslyInAnotherThread (token:CancellationToken, computation, timeout) =
let token, innerCTS =
// If timeout is provided, we govern the async by our own CTS, to cancel
// when execution times out. Otherwise, the user-supplied token governs the async.
match timeout with
| None -> token, None
| Some _ ->
let subSource = new LinkedSubSource(token)
subSource.Token, Some subSource
use resultCell = new ResultCell<AsyncResult<_>>()
QueueAsync
token
(fun res -> resultCell.RegisterResult(AsyncResult.Ok res, reuseThread=true))
(fun edi -> resultCell.RegisterResult(AsyncResult.Error edi, reuseThread=true))
(fun exn -> resultCell.RegisterResult(AsyncResult.Canceled exn, reuseThread=true))
computation
|> unfake
let res = resultCell.TryWaitForResultSynchronously(?timeout = timeout)
match res with
| None -> // timed out
// issue cancellation signal
if innerCTS.IsSome then innerCTS.Value.Cancel()
// wait for computation to quiesce; drop result on the floor
resultCell.TryWaitForResultSynchronously() |> ignore
// dispose the CancellationTokenSource
if innerCTS.IsSome then innerCTS.Value.Dispose()
raise (System.TimeoutException())
| Some res ->
match innerCTS with
| Some subSource -> subSource.Dispose()
| None -> ()
res.Commit()
[<DebuggerHidden>]
let RunSynchronouslyInCurrentThread (cancellationToken:CancellationToken, computation) =
use resultCell = new ResultCell<AsyncResult<_>>()
let trampolineHolder = new TrampolineHolder()
trampolineHolder.ExecuteWithTrampoline (fun () ->
let ctxt =
AsyncActivation.Create
cancellationToken
trampolineHolder
(fun res -> resultCell.RegisterResult(AsyncResult.Ok res, reuseThread=true))
(fun edi -> resultCell.RegisterResult(AsyncResult.Error edi, reuseThread=true))
(fun exn -> resultCell.RegisterResult(AsyncResult.Canceled exn, reuseThread=true))
computation.Invoke ctxt)
|> unfake
let res = resultCell.TryWaitForResultSynchronously().Value
res.Commit()
[<DebuggerHidden>]
let RunSynchronously cancellationToken (computation: Async<'T>) timeout =
// Reuse the current ThreadPool thread if possible. Unfortunately
// Thread.IsThreadPoolThread isn't available on all profiles so
// we approximate it by testing synchronization context for null.
match SynchronizationContext.Current, timeout with
| null, None -> RunSynchronouslyInCurrentThread (cancellationToken, computation)
// When the timeout is given we need a dedicated thread
// which cancels the computation.
// Performing the cancellation in the ThreadPool eg. by using
// Timer from System.Threading or CancellationTokenSource.CancelAfter
// (which internally uses Timer) won't work properly
// when the ThreadPool is busy.
//
// And so when the timeout is given we always use the current thread
// for the cancellation and run the computation in another thread.
| _ -> RunSynchronouslyInAnotherThread (cancellationToken, computation, timeout)
[<DebuggerHidden>]
let Start cancellationToken (computation:Async<unit>) =
QueueAsync
cancellationToken
(fun () -> fake()) // nothing to do on success
(fun edi -> edi.ThrowAny()) // raise exception in child
(fun _ -> fake()) // ignore cancellation in child
computation
|> unfake
[<DebuggerHidden>]
let StartWithContinuations cancellationToken (computation:Async<'T>) cont econt ccont =
let trampolineHolder = new TrampolineHolder()
trampolineHolder.ExecuteWithTrampoline (fun () ->
let ctxt = AsyncActivation.Create cancellationToken trampolineHolder (cont >> fake) (econt >> fake) (ccont >> fake)
computation.Invoke ctxt)
|> unfake
[<DebuggerHidden>]
let StartAsTask cancellationToken (computation:Async<'T>) taskCreationOptions =
let taskCreationOptions = defaultArg taskCreationOptions TaskCreationOptions.None
let tcs = new TaskCompletionSource<_>(taskCreationOptions)
// The contract:
// a) cancellation signal should always propagate to the computation
// b) when the task IsCompleted -> nothing is running anymore
let task = tcs.Task
QueueAsync
cancellationToken
(fun r -> tcs.SetResult r |> fake)
(fun edi -> tcs.SetException edi.SourceException |> fake)
(fun _ -> tcs.SetCanceled() |> fake)
computation
|> unfake
task
// Helper to attach continuation to the given task.
[<DebuggerHidden>]
let taskContinueWith (task: Task<'T>) (ctxt: AsyncActivation<'T>) useCcontForTaskCancellation =
let continuation (completedTask: Task<_>) : unit =
ctxt.trampolineHolder.ExecuteWithTrampoline (fun () ->
if completedTask.IsCanceled then
if useCcontForTaskCancellation then
ctxt.OnCancellation ()
else
let edi = ExceptionDispatchInfo.Capture(TaskCanceledException completedTask)
ctxt.CallExceptionContinuation edi
elif completedTask.IsFaulted then
let edi = ExceptionDispatchInfo.RestoreOrCapture completedTask.Exception
ctxt.CallExceptionContinuation edi
else
ctxt.cont completedTask.Result) |> unfake
task.ContinueWith(Action<Task<'T>>(continuation)) |> ignore |> fake
[<DebuggerHidden>]
let taskContinueWithUnit (task: Task) (ctxt: AsyncActivation<unit>) useCcontForTaskCancellation =
let continuation (completedTask: Task) : unit =
ctxt.trampolineHolder.ExecuteWithTrampoline (fun () ->
if completedTask.IsCanceled then
if useCcontForTaskCancellation then
ctxt.OnCancellation ()
else
let edi = ExceptionDispatchInfo.Capture(new TaskCanceledException(completedTask))
ctxt.CallExceptionContinuation edi
elif completedTask.IsFaulted then
let edi = ExceptionDispatchInfo.RestoreOrCapture completedTask.Exception
ctxt.CallExceptionContinuation edi
else
ctxt.cont ()) |> unfake
task.ContinueWith(Action<Task>(continuation)) |> ignore |> fake
[<Sealed; AutoSerializable(false)>]
type AsyncIAsyncResult<'T>(callback: System.AsyncCallback, state:obj) =
// This gets set to false if the result is not available by the
// time the IAsyncResult is returned to the caller of Begin
let mutable completedSynchronously = true
let mutable disposed = false
let cts = new CancellationTokenSource()
let result = new ResultCell<AsyncResult<'T>>()
member s.SetResult(v: AsyncResult<'T>) =
result.RegisterResult(v, reuseThread=true) |> unfake
match callback with
| null -> ()
| d ->
// The IASyncResult becomes observable here
d.Invoke (s :> System.IAsyncResult)
member s.GetResult() =
match result.TryWaitForResultSynchronously (-1) with
| Some (AsyncResult.Ok v) -> v
| Some (AsyncResult.Error edi) -> edi.ThrowAny()