Skip to content

Instantly share code, notes, and snippets.

@sebfia
Last active April 6, 2018 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebfia/d94a0ed8df8d8063665fa2c5f40a7fd5 to your computer and use it in GitHub Desktop.
Save sebfia/d94a0ed8df8d8063665fa2c5f40a7fd5 to your computer and use it in GitHub Desktop.
Extensions for Async
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