2

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)
2
  • I just verified this works using F# Interactive on "Mono JIT compiler version 2.8.1 (tarball Mon Nov 22 09:52:37 MST 2010)" (MacBook). By "only got something around 3000" messages, were they in order? 2000, 2001, 2002, etc? Were there skips? Were the skips periodic? Commented Mar 1, 2011 at 16:19
  • Hi, Chris, they were in order and no skips. I didn't run the code in FSI, which seems to be the cause. Perhaps that was the way Don was expecting the reader to run the code. Just followed the tip from desco and it resolved the issue. Commented Mar 1, 2011 at 16:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that was it. Thanks for quick response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.