Lay González
Lay González

Reputation: 2985

Solution for common async pattern: Start many, await first, cancel the rest

I'm looking for this pattern:

let startManyAwaitFirstCancelRest (n:Async<'T> list) : Async<'T> =
    // start the n asyncs,
    // return the result of the first to finish and
    // cancel the rest.

Upvotes: 0

Views: 86

Answers (1)

desco
desco

Reputation: 16782

something like this?

open System
open System.Threading
open System.Threading.Tasks

let run (asyncs: list<Async<'T>>): Async<'T> =
    let cts = new CancellationTokenSource()
    let tasks = asyncs |> List.map (fun a -> Async.StartAsTask(a, cancellationToken = cts.Token))
    async {
        let! t = Async.AwaitTask ((Task.WhenAny tasks).Unwrap())
        do cts.Cancel()
        return t
    }

Upvotes: 2

Related Questions