开发者

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. 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 messa开发者_运维技巧ge '%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)


Just run your code in Win machine - everything is OK. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜