F# using Async.Parallel to run 2 tasks in parallel

asynchronous, f#

Solution

`Async.Parallel` takes a sequence of async. In this case I pass it a list.

[dowork 1; work 2]
|> Async.Parallel
|> Async.RunSynchronously
|> ignore

If you want to return different types of data use a Discriminated Union.

type WorkResults =
    | DoWork of int
    | Work of float32

let dowork n =
    async {
        do printfn "work %d" n
        return DoWork(n)
    }

let work i = async {
  do! Async.Sleep(2000)
  printfn "work finished %d" i 
  return Work(float32 i / 4.0f)
}

[dowork 1; work 2]
|> Async.Parallel
|> Async.RunSynchronously
|> printf "%A"

output

work 1
work finished 2
[|DoWork 1; Work 0.5f|]

Problem

Assuming I have these two functions: ``` let dowork n = async { do printfn "work %d" n } let work i = async { do! Async.Sleep(2000) printfn "work finished %d" i } ``` How would I use Async.Parallel to run them concurrently and wait for both to finish before proceeding?

Original source

Related problems