concept mailbox in category c#

appears as: mailbox, The mailbox, mailbox
Real-World Functional Programming with Examples in F# and C#

This is an excerpt from Manning's book Real-World Functional Programming with Examples in F# and C#.

To create a mailbox processor, we use the Start member of the MailboxProcessor type. It initializes the mailbox for the messages and runs the specified function ❶ to start processing messages. The function returns an asynchronous workflow that can wait for messages using the Receive method ❷ of the mailbox that we get as an argument during the initialization.

The code for the threads is quite simple. Both functions contain an infinite loop that would execute useful work in a real application, and both occasionally send messages to the mailbox to synchronize. The first function only uses the ModifyState message ❶, and the second one first sends the message to block the mailbox, then waits for some time and unblocks it ❷. We use Async.Start to start executing the functions in three thread pool threads by creating a list of function values representing the processes to run and then starting each of them in a for loop. The list contains the modifyThread function twice, so we’ll have two threads sending updates to the state.

Let’s analyze the behavior of the application when we execute it. The application prints the time of an operation, so you can run it and look at the printed times. It starts off by processing the incoming ModifyState messages for about 2 seconds. The blocking/resuming thread then sends the Block message, so nothing will be printed to the console for the next 1.5 seconds, even though new ModifyState messages will still be posted to the mailbox. After that, the mailbox processor will be resumed and it’ll process all the queued ModifyState messages, so the state will be updated several times in quick succession. It will continue running, processing messages as they arrive for the next 2 seconds until the next Block message is received.