如何等待异步完成 [英] How to wait for async to finish

查看:137
本文介绍了如何等待异步完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一些异步工作流程,然后等待它打印一些成果之前完成,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆