Home
Insert
Update snippet 'Async.AwaitTask with timeouts'
Title
Passcode
Description
Asynchronously await task completion with timeout support.
Source code
// based on http://stackoverflow.com/a/11191070 open System open System.Threading open System.Threading.Tasks type Microsoft.FSharp.Control.Async with static member AwaitTask (t : Task<'T>, timeout : int) = async { use cts = new CancellationTokenSource() use timer = Task.Delay (timeout, cts.Token) let! completed = Async.AwaitTask <| Task.WhenAny(t, timer) if completed = (t :> Task) then cts.Cancel () let! result = Async.AwaitTask t return Some result else return None } // example Async.AwaitTask((Task.Delay 500).ContinueWith(fun _ -> 42), 600) |> Async.RunSynchronously
Tags
awaittask
timeout
awaittask
timeout
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update