如何在异步块中终止循环?

时间:2013-10-28 21:10:11

标签: f# f#-3.0

我使用Tomas'BlockingQueueAgent并创建了一个F#控制台程序。

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

我有以下代码。但是,该计划永远不会结束。如何在消费者中退出循环?

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 个答案:

答案 0 :(得分:3)

正如ildjarn建议的那样,使用递归而不是循环:

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" }