Last active
April 6, 2018 04:17
-
-
Save sebfia/d94a0ed8df8d8063665fa2c5f40a7fd5 to your computer and use it in GitHub Desktop.
Extensions for Async
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
module Async | |
open System.Threading.Tasks | |
let ForEach<'T> (computations: Async<'T> list) = | |
let rec forEach l r = | |
async { | |
match l with | |
| f::t -> | |
let! x = f | |
return! x::r |> forEach t | |
| [] -> return r |> List.rev | |
} | |
async { | |
return! forEach computations [] | |
} | |
let inline StartAsPlainTask (work : Async<unit>) = Task.Factory.StartNew(fun () -> work |> Async.RunSynchronously) | |
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 | |
| _ -> () | |
task.ContinueWith continuation |> Async.AwaitTask | |
let inline tryRunTask task = | |
async { | |
let! result = task |> awaitPlainTask |> Async.Catch | |
match result with | |
| Choice2Of2 ex -> return Result.Error ex | |
| _ -> return Result.Ok () | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment