Created
June 21, 2018 20:53
-
-
Save eulerfx/9f8cb2f9879a98cd0675edb42b005efe to your computer and use it in GitHub Desktop.
F# Async Timeout
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 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