无法通过邮箱处理器(F#)保持状态

时间:2019-05-11 21:56:13

标签: asynchronous f# mailboxprocessor

我正在尝试创建一个字符串列表,该列表将在邮箱处理器的帮助下逐步将元素逐渐异步插入。但是我没有得到想要的输出。

我几乎遵循https://fsharpforfunandprofit.com/posts/concurrency-actor-model/中的代码 但是,对于我来说,它似乎没有达到预期的效果。我的代码如下:

type TransactionQueue ={

queue : string list

} with

static member UpdateState (msg : string) (tq : TransactionQueue) =
    {tq with queue = (msg :: tq.queue)}

static member Agent = MailboxProcessor.Start(fun inbox ->
                            let rec msgLoop (t : TransactionQueue) =
                                async{
                                   let! msg = inbox.Receive()
                                   let newT = TransactionQueue.UpdateState msg t
                                   printfn "%A" newT
                                   return! msgLoop newT
                                }
                            msgLoop {queue = []}
                        )

static member Add i = TransactionQueue.Agent.Post i



[<EntryPoint>]
let main argv =

// test in isolation
printfn "welcome to test"
let rec loop () =
    let str = Console.ReadLine()
    TransactionQueue.Add str
    loop ()

loop ()



0 

我一直得到的结果只是最新输入的列表,不保留状态。因此,如果我输入“ a”,然后输入“ b”,然后输入“ c”,则队列将仅具有值“ c”,而不是“ a”;“ b”;“ c”

任何帮助或指针将不胜感激!

1 个答案:

答案 0 :(得分:2)

就像 C# Properties一样,您的Agent实际上是一个属性,因此其行为类似于带有void参数的方法。这就是为什么每次访问Agent属性时都会获得一个新代理的原因。

在惯用的F#中,实现代理时有两种样式。如果您不需要很多代理实例,只需编写一个模块,然后将与代理相关的内容封装在其中。否则,应使用OOP样式。

样式#1的代码

module TransactionQueue =
    type private Queue = Queue of string list
    let private empty = Queue []
    let private update item (Queue items) = Queue (item :: items)
    let private agent = MailboxProcessor.Start <| fun inbox ->
        let rec msgLoop queue = async {
            let! msg = inbox.Receive ()
            return! queue |> update msg |> msgLoop
        }
        msgLoop empty
    let add item = agent.Post item

[<EntryPoint>]
let main argv =
    // test in isolation
    printfn "welcome to test"
    let rec loop () =
        let str = Console.ReadLine()
        TransactionQueue.add str
        loop ()
    loop ()

样式2的代码

type Queue = Queue of string list with
    static member Empty = Queue []
    static member Update item (Queue items) =
        Queue (item :: items)

type Agent () =
    let agent = MailboxProcessor.Start <| fun inbox ->
        let rec msgLoop queue = async {
            let! msg = inbox.Receive ()
            return! queue |> Queue.Update msg |> msgLoop
        }
        msgLoop Queue.Empty
    member this.Add item = agent.Post item

[<EntryPoint>]
let main argv =
    // test in isolation
    printfn "welcome to test"
    let agent = new Agent ()
    let rec loop () =
        let str = Console.ReadLine()
        agent.Add str
        loop ()
    loop ()

请注意,Queue类型使用Single-case union types