Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
F# - helper functions to Start and Wait for a plain Task (not Task<T>)
open System.Threading.Tasks
[<AutoOpen>]
module Async =
let inline awaitPlainTask (task: Task) =
// rethrow exception from preceding task if it fauled
let continuation (t : Task) : unit =
match t.IsFaulted with
| true -> raise t.Exception
| arg -> ()
task.ContinueWith continuation |> Async.AwaitTask
let inline startAsPlainTask (work : Async<unit>) = Task.Factory.StartNew(fun () -> work |> Async.RunSynchronously)
/// Usage
> let sleepy = async {
do! Async.Sleep(5000) // sleep for 5 seconds
printfn "awake"
};;
val sleepy : Async<unit>
sleepy |> Async.startAsPlainTask;;
val it : Task = System.Threading.Tasks.Task {AsyncState = null;
CreationOptions = None;
Exception = null;
Id = 2;
IsCanceled = false;
IsCompleted = false;
IsFaulted = false;
Status = Running;}
// 5 seconds later
> awake
> let sleepy2 = async {
do! sleepy |> Async.startAsPlainTask |> Async.awaitPlainTask
printfn "feeling sleepy again..."
};;
val sleepy2 : Async<unit>
> sleepy2 |> Async.Start;;
val it : unit = ()
// 5 seconds later..
> awake
feeling sleepy again...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.