gpt4 book ai didi

f# - 等待邮箱处理器

转载 作者:行者123 更新时间:2023-12-04 03:00:33 24 4
gpt4 key购买 nike

是否可以等待邮箱处理器,以下代码在 F# 交互式中工作,但有没有办法在应用程序或单元测试中等待它?

[<TestMethod>]
member this.TestMailboxProcessor() =
let mailboxProcessor = MailboxProcessor<string>.Start(fun inbox ->
async {
while true do
let! msg = inbox.Receive()
printfn "agent got message %s" msg // too late, UnitTest exits
}
)

mailboxProcessor.Post "ping"
Console.WriteLine "message posted" // I see this in the console
Assert.IsTrue(true)

最佳答案

在这种情况下这是不可能的,但您可以定义您的消息类型以包含 AsyncReplyChannel<'t> ,然后允许您使用 MailboxProcessor.PostAndReply而不是邮政。通过这种方式,调用代码可以(同步或异步)等待响应值,或者至少是处理完成的指示。

您修改后的源代码可能如下所示:

[<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 是一个有点棘手的话题,所以请确保您始终使用超时,否则如果您的代码出现错误,或异常终止消息循环,您的代码将永远挂起。在测试中不好,在生产中更糟。

关于f# - 等待邮箱处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49620700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com