4

是否可以创建一个仅有时发布回复的邮箱代理?从外观上看,在我看来,如果您想发布回复,您必须始终发送异步回复频道。

对于我的用例,我真的希望能够灵活地使某些消息只需要传递给代理,而其他消息我希望得到同步或异步回复。

4

1 回答 1

9

我不确定我是否正确理解了这个问题 - 但您当然可以使用有区别的联合作为您的消息类型。然后你可以有一些包含它的案例(消息类型)AsyncReplyChannel<T>和一些不携带它的其他消息(并且不需要回复)。

例如,对于添加数字的简单代理,您可以拥有Add(不需要响应)并且Get确实需要响应。此外,Get带有一个布尔值,指定我们是否应该将状态重置为零:

type Message = 
  | Add of int
  | Get of bool * AsyncReplyChannel<int>

代理然后重复接收消息,如果消息是Get则它发送回复:

let counter = MailboxProcessor.Start(fun inbox -> 
  let rec loop count = async {
    let! msg = inbox.Receive()
    match msg with 
    | Add n -> return! loop (count + n) // Just update the number
    | Get (reset, repl) ->
        repl.Reply(count)               // Reply to the caller 
        let count = if reset then 0 else count // get new state
        return! loop count }            // .. and continue in the new state
  loop 0 )

然后,您可以使用Post方法发送不需要回复PostAndReply的消息,并通过异步回复通道发送返回某些内容的消息:

counter.Post(Add 10)
counter.PostAndReply(fun r -> Get(true, r))
counter.PostAndReply(fun r -> Get(false, r))
于 2013-09-30T20:00:54.403 回答