是否可以创建一个仅有时发布回复的邮箱代理?从它的外观来看,在我看来,如果您想发布回复,您必须始终发送一个异步回复 channel 。
对于我的用例,我真的希望能够灵活地将某些消息只需要传递给代理,而其他消息我希望得到同步或异步回复。
最佳答案
我不确定我是否正确理解了这个问题——但你当然可以使用受歧视的联合作为你的消息类型。然后你可以有一些包含 AsyncReplyChannel<T>
的案例(消息类型)。以及其他一些不携带它的消息(并且不需要回复)。
例如,对于添加数字的简单代理,您可以拥有 Add
(不需要响应)和 Get
这确实需要回应。另外,Get
带有一个 bool 值,指定我们是否应该将状态重置为零:
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
发送通过异步回复 channel 返回某些内容的消息:counter.Post(Add 10)
counter.PostAndReply(fun r -> Get(true, r))
counter.PostAndReply(fun r -> Get(false, r))
关于f# - 创建一个只有一些消息得到响应的代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102563/