1

I'm use Tomas' BlockingQueueAgent and created an F# console program.

https://github.com/tpetricek/FSharp.AsyncExtensions/blob/master/src/Agents/BlockingQueueAgent.fs

I have the following code. However, the program never end. How to exit the loop in the consumer?

let producer() = 
    let addLinks = async {
        for url in links do
            do! ag.AsyncAdd(Some (url))
            printfn "Producing %s" url }
    async { do! addLinks
            do! ag.AsyncAdd(None) }

let consumer() = async {
    while true do 
        let! item = ag.AsyncGet()
        match item with 
        | Some (url) ->
            printfn "Consuming  %s" url
            ....
        | None -> 
            printfn "Done" } // How to exit the loop from here?

producer() |> Async.Start
consumer() |> Async.RunSynchronously
1
  • 1
    Use recursion instead of a loop. Commented Oct 28, 2013 at 21:15

1 Answer 1

4

As ildjarn suggests, use recursion instead of a loop:

let rec consumer() = async {
    let! item = ag.AsyncGet()
    match item with
    | Some(url) ->
        printfn "Consuming %s" url
        ...
        return! consumer() // recursive call only in this case
    | None -> 
        printfn "Done" }
Sign up to request clarification or add additional context in comments.

2 Comments

Curiously, is there any way to do it without using recursive function?
@dc7a9163d9 - sure - use a ref cell's value as the guard condition for the while loop and set it to false when you hit a None.

Your Answer

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.