-
-
Save lessismore1/169c41b8c4ff7ed0372b07adc496098d to your computer and use it in GitHub Desktop.
F# - helper functions to Start and Wait for a plain Task (not Task<T>)
This file contains 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
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