Skip to content

Instantly share code, notes, and snippets.

@davidglassborow
Forked from eulerfx/Async.Timeout.fs
Created June 28, 2018 12:26
Show Gist options
  • Save davidglassborow/8882eaf533105c8cc6f16b2e4efbf4f3 to your computer and use it in GitHub Desktop.
Save davidglassborow/8882eaf533105c8cc6f16b2e4efbf4f3 to your computer and use it in GitHub Desktop.
F# Async Timeout
let timeoutNone (timeoutMs:int) (a:Async<'a>) : Async<'a option> = async {
let! ct = Async.CancellationToken
let res = TaskCompletionSource<_>()
use cts = CancellationTokenSource.CreateLinkedTokenSource ct
res.Task.ContinueWith (fun _ -> cts.Cancel ()) |> ignore
use timer = new Timer((fun _ -> res.TrySetResult None |> ignore), null, timeoutMs, Timeout.Infinite)
Async.StartThreadPoolWithContinuations (
a,
(fun a -> res.TrySetResult (Some a) |> ignore),
(fun e -> res.TrySetException e |> ignore),
(fun _ -> res.TrySetResult None |> ignore),
cts.Token)
return! res.Task |> Async.AwaitTask }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment