简体   繁体   English

与MailboxProcessor一起使用时,为什么此F#代码未生成预期的输出?

[英]Why this F# code does not generate expected output when used with MailboxProcessor?

I was going through one of Don Syme's blog posts Async and Parallel Design Patterns in F#: Agents . 我正在看Don Syme的博客文章之一《 F#:Agents中的Async和Parallel Design Patterns》 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. 在Ubuntu下使用Mono 2.8.1只能得到大约3000条消息,而在Windows XP下使用Visual F#只能得到15条消息,而不是预期的10,000条消息。 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. 顺便说一句,我试图用以下File op替换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)

Just run your code in Win machine - everything is OK. 只需在Win机器上运行您的代码-一切正常。 Try to add 尝试添加

ignore( System.Console.ReadKey() )

as a last line, because agent.Post is non-blocking and after posting 10000 messages control flow will move forward, possibly exiting the program. 最后一行,因为agent.Post是非阻塞的,并且在发布10000条消息之后,控制流将向前移动,可能会退出程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM