常见异步模式的解决方案:开始很多,先等待,取消其余
Solution for common async pattern: Start many, await first, cancel the rest
我正在寻找这种模式:
let startManyAwaitFirstCancelRest (n:Async<'T> list) : Async<'T> =
// start the n asyncs,
// return the result of the first to finish and
// cancel the rest.
是这样的吗?
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
}
我正在寻找这种模式:
let startManyAwaitFirstCancelRest (n:Async<'T> list) : Async<'T> =
// start the n asyncs,
// return the result of the first to finish and
// cancel the rest.
是这样的吗?
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
}