Skip to content

Instantly share code, notes, and snippets.

@eulerfx
Created June 21, 2018 20:45
Show Gist options
  • Save eulerfx/c41d50c6fba8e88cf16a21ed7c3c14bd to your computer and use it in GitHub Desktop.
Save eulerfx/c41d50c6fba8e88cf16a21ed7c3c14bd to your computer and use it in GitHub Desktop.
F# Async Cancellation Helper
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