簡體   English   中英

與MailboxProcessor一起使用時,為什么此F#代碼未生成預期的輸出?

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

我正在看Don Syme的博客文章之一《 F#:Agents中的Async和Parallel Design Patterns》 但是,以下看似極其簡單的代碼並未產生預期的輸出。

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條消息,而在Windows XP下使用Visual F#只能得到15條消息,而不是預期的10,000條消息。 我在這里想念什么嗎? 順便說一句,我試圖用以下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)

只需在Win機器上運行您的代碼-一切正常。 嘗試添加

ignore( System.Console.ReadKey() )

最后一行,因為agent.Post是非阻塞的,並且在發布10000條消息之后,控制流將向前移動,可能會退出程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM