如何等待异步完成 [英] How to wait for async to finish
问题描述
我想运行一些异步工作流程,然后等待它打印一些成果之前完成,例如:
I would like to run some async workflow, then wait for it to finish before printing some results, example:
let dowork n =
async {
do printfn "work %d" n
}
let creatework() =
async {
for x in [1..5] do
Async.Start(dowork x)
}
Async.RunSynchronously(creatework())
printfn "finished"
当我运行这一点,我希望所有的DoWork的调用打印完成之前完成。不过,我得到这样的结果:
when I run this, I want all the dowork calls to finish before printing "finished". However I get results like this:
工作2
工作3
工作4
工作5
完
工作1
work 2 work 3 work 4 work 5 finished work 1
我曾尝试去除creatework异步(),但已完成的工作流程异步运行之前被打印出来。
I have tried removing async from creatework() but "finished" is printed before the async workflows are run.
在实际DoWork的,程序执行一些IO,所以我想等待最慢的继续之前完成。
In the real dowork, the program performs some IO, so I want to wait for the slowest one to finish before continuing.
推荐答案
好回答我的问题似乎有点扯,但这个似乎工作。有人拿出更好的东西,所以我可以奖励他们的答案:)
Well answering my own question seems lame, but this seems to work. Someone come up with something better so I can award them the answer :)
let dowork n =
async {
do printfn "work %d" n
}
let creatework() =
[1..5] |> Seq.map dowork |> Async.Parallel |> Async.RunSynchronously
creatework()
printfn "finished"
它给出了不同的输出,但拍完到目前为止总是在最后...
It gives various output, but "finished" so far is always last...
这篇关于如何等待异步完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!