我正在寻找这种模式:
let startManyAwaitFirstCancelRest (n:Async<'T> list) : Async<'T> =
// start the n asyncs,
// return the result of the first to finish and
// cancel the rest.
答案 0 :(得分:2)
这样的事情?
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
}