f# - 创建一个只有一些消息得到响应的代理?

标签 f# mailboxprocessor

是否可以创建一个仅有时发布回复的邮箱代理?从它的外观来看,在我看来,如果您想发布回复,您必须始终发送一个异步回复 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/

相关文章:

unit-testing - 如何在F#中保持方法返回类型 'void'?

f# - f# 中的嵌套泛型类型推断

asynchronous - MailboxProcessor.Dispose 不会使对象 GC 可收集

f# - F# 中的匹配字符范围

f# - 在远程邮箱处理器之间传递消息?

c# - 将属性应用于返回值 - 在 F# 中

f# - 等待邮箱处理器

asynchronous - 如何在异步工作流程中使用 Async.Parallel?

f# - 邮箱处理器和异常