为什么此 F# 代码在与 MailboxProcessor 一起使用时不会生成预期的输出?
我正在阅读 Don Syme 的一篇博客文章 F# 中的异步和并行设计模式:代理。然而,下面看似极其简单的代码并没有产生预期的输出。
type Agent<'T> = MailboxProcessor<'T>
let agent =
Agent.Start(fun inbox ->
async { while true do
let! msg = inbox.Receive()
printfn "got message '%s'" msg } )
for i in 1 .. 10000 do
agent.Post (sprintf "message %d" i)
我在 Ubuntu 下使用 Mono 2.8.1 只收到了大约 3000 条消息,而不是预期的 10,000 条消息,或者在 Windows XP 下使用 Visual F# 收到了 15 条消息。我在这里错过了什么吗?顺便说一句,我尝试用以下文件操作替换 printfn 语句,并最终得到相同的部分结果。
open System.IO
type Agent<'T> = MailboxProcessor<'T>
let agent =
Agent.Start(fun inbox ->
async { while true do
let! msg = inbox.Receive()
use logger = new StreamWriter("a.log", true)
logger.WriteLine("got message '{0}'", msg.ToString())
logger.Close()
} )
for i in 1 .. 10000 do
agent.Post (sprintf "message %d" i)
I was going through one of Don Syme's blog posts Async and Parallel Design Patterns in F#: Agents. However, the following seemingly extremely simple code did not generate output as expected.
type Agent<'T> = MailboxProcessor<'T>
let agent =
Agent.Start(fun inbox ->
async { while true do
let! msg = inbox.Receive()
printfn "got message '%s'" msg } )
for i in 1 .. 10000 do
agent.Post (sprintf "message %d" i)
Instead of expected 10,000 messages , I only got something around 3000 messages using Mono 2.8.1 under Ubuntu, or 15 messages using Visual F# under Windows XP. Am I missing anything here? BTW, I tried to replace the printfn statement with the following File op and ended up with same partial results.
open System.IO
type Agent<'T> = MailboxProcessor<'T>
let agent =
Agent.Start(fun inbox ->
async { while true do
let! msg = inbox.Receive()
use logger = new StreamWriter("a.log", true)
logger.WriteLine("got message '{0}'", msg.ToString())
logger.Close()
} )
for i in 1 .. 10000 do
agent.Post (sprintf "message %d" i)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在 Win 机器中运行您的代码即可 - 一切正常。尝试添加
为最后一行,因为 agent.Post 是非阻塞的,并且在发布 10000 条消息后控制流将向前移动,可能会退出程序。
Just run your code in Win machine - everything is OK. Try to add
as a last line, because agent.Post is non-blocking and after posting 10000 messages control flow will move forward, possibly exiting the program.