Skip to content

Instantly share code, notes, and snippets.

@eulerfx
Created June 21, 2018 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eulerfx/9f8cb2f9879a98cd0675edb42b005efe to your computer and use it in GitHub Desktop.
Save eulerfx/9f8cb2f9879a98cd0675edb42b005efe 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