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
ca9163d9
29.6k74 gold badges252 silver badges467 bronze badges
1 Answer 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.
Sign up to request clarification or add additional context in comments.
3 Comments
Jarak
I'm reasonably certain that simply putting
Async.Parallel |> before the Async.RunSynchronously would work fine also.ajuch
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.Jarak
Ah, yes, you're right. Somehow I had misread the code and thought that there were multiple
asyncs joined up.lang-ml