Let's first create a simple "Hello world!" MailboxProcessor
which processes one type of message and prints greetings.
You'll need the message type. It can be anything, but Discriminated Unions are a natural choice here as they list all the possible cases on one place and you can easily use pattern matching when processing them.
// In this example there is only a single case, it could technically be just a string
type GreeterMessage = SayHelloTo of string
Now define the processor itself. This can be done with MailboxProcessor<'message>.Start
static method which returns a started processor ready to do its job. You can also use the constructor, but then you need to make sure to start the processor later.
let processor = MailboxProcessor<GreeterMessage>.Start(fun inbox ->
let rec innerLoop () = async {
// This way you retrieve message from the mailbox queue
// or await them in case the queue empty.
// You can think of the `inbox` parameter as a reference to self.
let! message = inbox.Receive()
// Now you can process the retrieved message.
match message with
| SayHelloTo name ->
printfn "Hi, %s! This is mailbox processor's inner loop!" name
// After that's done, don't forget to recurse so you can process the next messages!
innerLoop()
}
innerLoop ())
The parameter to Start
is a function which takes a reference to the MailboxProcessor
itself (which doesn't exist yet as you are just creating it, but will be available once the function executes). That gives you access to its various Receive
and Scan
methods to access the messages from the mailbox. Inside this function, you can do whatever processing you need, but a usual approach is an infinite loop that reads the messages one by one and calls itself after each one.
Now the processor is ready, but it doesn't to anything! Why? You need to send it a message to process. This is done with the Post
method variants - let's use the most basic, fire-and-forget one.
processor.Post(SayHelloTo "Alice")
This puts a message to processor
's internal queue, the mailbox, and immediately returns so that the calling code can continue. Once the processor retrieves the message, it will process it, but that will be done asynchronously to posting it, and it will be most likely done on a separate thread.
Very soon afterwards you should see the message "Hi, Alice! This is mailbox processor's inner loop!"
printed to the output and you're ready for more complicated samples.