常见异步模式的解决方案:启动多个,等待第一个,取消其余模式

时间:2015-06-02 18:26:35

标签: .net asynchronous f#

我正在寻找这种模式:

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

1 个答案:

答案 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
    }