Reputation: 29159
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?
Upvotes: 1
Views: 89
Reputation: 415
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.
Upvotes: 1