在异步工作流程中并行运行功能?

时间:2019-01-10 06:09:21

标签: f#

以下代码

let doWork n = async {
    [1..5]
    |> Seq.iter(fun i ->
        System.Threading.Thread.Sleep 1000 // Simulate working
        printfn "%s runs %i seconds" n i
        )
}

let f1 = async {
    do! doWork "f1"
    return 1
}

async {
    let a = f1
    do! doWork "main"
    let! i = a
} |> Async.RunSynchronously

并打印以下结果。它显示了两个doWork调用顺序运行。

main runs 1 seconds
main runs 2 seconds
main runs 3 seconds
main runs 4 seconds
main runs 5 seconds
f1 runs 1 seconds
f1 runs 2 seconds
f1 runs 3 seconds
f1 runs 4 seconds
f1 runs 5 seconds

但是,我希望doWork调用的f1和主代码并行运行吗?

1 个答案:

答案 0 :(得分:1)

像这样尝试:

let computation () = async {
  printfn "Start work"
  do! Async.Sleep(100)
  printfn "Finished work"
}

let s = seq {
  for i in 1 .. 10 do
    let c = computation()
    yield c
}

s |> Async.Parallel |> Async.Ignore |> Async.Start

Async.ParallelAsync<unit> list转换为Async<unit []>,然后可以并行运行。