1

The following code

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

And it prints the following result. It shows that the two doWork calls run sequentially.

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

However, I want the doWork called by f1 and the main code be running in parallel?

asked Jan 10, 2019 at 6:09

1 Answer 1

1

Try it like this:

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.Parallel converts the Async<unit> list to Async<unit []> which can be run in parallel then.

answered Jan 10, 2019 at 8:26
Sign up to request clarification or add additional context in comments.

3 Comments

I'm reasonably certain that simply putting Async.Parallel |> before the Async.RunSynchronously would work fine also.
If you're refering to the original question's code, I'd say no... Async.Parallel's signature is seq<Async<'T>> -> Async<'T []>. It cannot parallelize a single async, only a sequence of asyncs.
Ah, yes, you're right. Somehow I had misread the code and thought that there were multiple asyncs joined up.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.