Actor programming with MailboxProcessor
The actor programming model is a concurrent programming technique that provides a powerful mechanism to encapsulate several concurrency features. The key principles of the actor model are as follows:
- No shared state between actors
- Async message passing between clients to actor or between actors
- Mailbox to buffer incoming messages
- React to received messages by executing function
The F# MailboxProcessor
class is the implementation of the actor model in FSharp.Core
, and it is essentially a dedicated message queue running its own thread. We can use the API for MailboxProcessor
to Post
/Receive
messages synchronously or asynchronously. We can also consider it an agent with an internal state machine. Let's take look at our first async agent:
let agent =
MailboxProcessor.Start(fun inbox ->
async { while true do
let! msg = inbox.Receive()
printfn "got message '%s'" msg } )
> agent.Post "Hello...