Created
June 21, 2018 20:45
-
-
Save eulerfx/c41d50c6fba8e88cf16a21ed7c3c14bd to your computer and use it in GitHub Desktop.
F# Async Cancellation Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let withCancellation (ct:CancellationToken) (a:Async<'a>) : Async<'a> = async { | |
let! ct2 = Async.CancellationToken | |
use cts = CancellationTokenSource.CreateLinkedTokenSource (ct, ct2) | |
let tcs = new TaskCompletionSource<'a>() | |
use _reg = cts.Token.Register (fun () -> tcs.TrySetCanceled() |> ignore) | |
let a = async { | |
try | |
let! a = a | |
tcs.TrySetResult a |> ignore | |
with ex -> | |
tcs.TrySetException ex |> ignore } | |
Async.Start (a, cts.Token) | |
return! tcs.Task |> Async.AwaitTask } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment