我在消息循环中有一个超时异常(我真的打算设置一个超时),我尝试按如下方式捕获它
let printerAgent = MailboxProcessor.Start(fun inbox->
// the message processing function
let rec messageLoop() = async{
try
// read a message
let! msg = inbox.Receive 30000
// process a message
match msg with
| Message text ->
sw.WriteLine("{0}: {1}", DateTime.UtcNow.ToShortTimeString(), text)
printfn "%s" text
// loop to top
return! messageLoop()
| Shutdown replyChannel ->
replyChannel.Reply()
// We do NOT do return! messageLoop() here
with
| exc ->
printfn "%s" exc.Message
}
// start the loop
messageLoop()
)
我可以看到控制台打印的超时消息,但程序永远不会结束:我错过了什么?
这就是我在代码中调用 printerAgent
的方式
printerAgent.PostAndReply( (fun replyChannel -> Shutdown replyChannel), 10000)
请注意,inbox.Receive()
最终会在几分钟后正常终止,但我的目标是设置超时(例如 30 秒)。
答案 0 :(得分:1)
我想我看到了概念的问题。我无法在收到最终关闭消息之前终止消息循环(否则程序发送的所有以下 printerAgent.Post
消息将在队列中保持未处理 >,不会因任何错误而阻塞程序,并且由 printerAgent.PostAndReply
发送的最终关闭消息将超时,也不会因任何错误而阻塞程序)。
我应该返回消息循环,以便它实际上可以在超时后继续正常接收消息:
with
| exc ->
printfn "%s" exc.Message
return! messageLoop() // important! I guess I can't really terminate the message loop from here
此时程序同时终止:我只看到控制台中打印了很多 Timeout of Mailbox.Receive
(当消息循环空闲等待接收消息时,每隔 n=30 秒,因此它们可以提供有关经过时间的信息)。