在这种情况下是不可能的,但是您可以定义您的消息类型以包含AsyncReplyChannel<'t>,这样您就可以使用MailboxProcessor.PostAndReply而不是 Post。这样,调用代码可以(同步或异步)等待响应值,或至少等待处理完成的指示。
您修改后的源代码可能如下所示:
[<TestMethod>]
member this.TestMailboxProcessor() =
let mailboxProcessor =
MailboxProcessor<string * AsyncReplyChannel<unit>>.Start(fun inbox ->
async {
while true do
let! msg, replyChannel = inbox.Receive()
printfn "agent got message %s" msg
(*
Reply takes a value of the generic param of
AsyncReplyChannel<'t>, in this case just a unit
*)
replyChannel.Reply()
}
)
(*
You can't create an AsyncReplyChannel<'t> value, but this does it for you.
Also always, always use timeouts when awaiting message replies.
*)
mailboxProcessor.PostAndReply(
(fun replyChannel -> "ping", replyChannel),
timeout = 1000)
(* This gets printed only after the message has been posted and processed *)
Console.WriteLine "message posted"
Assert.IsTrue(true)
MailboxProcessors 是一个有点棘手的话题,所以确保你总是使用超时,否则如果你的代码出错,或者异常终止消息循环,你的代码将永远挂起。在测试中不好,在生产中更糟。