我正在使用代理(MailboxProcessor)在需要响应的地方进行一些有状态的处理。
- 来电者使用
MailboxProcessor.PostAndAsyncReply
- 在代理内部,会给出一个响应
AsyncReplyChannel.Reply
但是,通过查看 f# 源代码,我发现在响应传递之前,代理不会处理下一条消息。总的来说,这是一件好事。但在我的情况下,代理更希望继续处理消息而不是等待响应传递。
做这样的事情来传递响应是否有问题?(或者有更好的选择吗?)
async { replyChannel.Reply response } |> Async.Start
我意识到这种方法并不能保证响应将按顺序传递。我没关系。
参考示例
// agent code
let doWork data =
async { ... ; return response }
let rec loop ( inbox : MailboxProcessor<_> ) =
async {
let! msg = inbox.Receive()
match msg with
| None ->
return ()
| Some ( data, replyChannel ) ->
let! response = doWork data
replyChannel.Reply response (* waits for delivery, vs below *)
// async { replyChannel.Reply response } |> Async.Start
return! loop inbox
}
let agent =
MailboxProcessor.Start(loop)
// caller code
async {
let! response =
agent.PostAndAsyncReply(fun replyChannel -> Some (data, replyChannel))
...
}