Chico
Chico

Reputation: 309

F# Using Return Values From Async

I'm trying to learn F# but I keep running into issues. The latest is using async. In the code below, I'm trying to run two long running operations and perform a calculation based on the result but I get an error "Async does not support the + operator". I have tried casting etc to get it to work but I'm not getting anywhere fast.

Could someone please explain where I'm going wrong.

Thanks.

let SumOfOpFaults =
    async{
        printfn "Getting Sum of Op Faults"
        return query {
            for a in AlarmResult do
            sumBy a.UserFaultTime
        }
    }

let SumOfMcFaults =
    async{
        printfn "Getting Sum of Machine Faults"
        return query {
            for a in AlarmResult do
            sumBy a.MachineFaultTime
        }
    }

[SumOfMcFaults; SumOfOpFaults]
|> Async.Parallel
|> Async.RunSynchronously
|> ignore

let total = SumOfOpFaults + SumOfMcFaults // <---Error Here

Upvotes: 6

Views: 3288

Answers (1)

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

SumOfOpFaults is defined as an Async<'T>. It will never change to a 'T so you can't use + on it later.

Async.Parallel turns any sequence of Async computations into one Async computation that runs them in parallel and returns an array.

Async.RunSynchronously doesn't give you a result by side effects, but as a return value. So you just need to do this:

let total =
    [SumOfMcFaults; SumOfOpFaults]
    |> Async.Parallel
    |> Async.RunSynchronously
    |> Array.sum

Upvotes: 10

Related Questions