Create returns a function matching the PeekCompletedCallBack delegate. There are two ways to read messages from a MessageQueue. Peeking, getting the message without removing it, and Receiving, getting the message and receiving it from the queue. Doing a Peek and posting the Peeked message to the port ensures that exceptions during message handling dont result in message loss. Ill explain how the message is removed in a moment. The PeekCompletedEventHandler function returned by Create with exception handling code removed appears below.

As youll see throughout the sample application, a MessageMapper class serializes and deserializes into and out of the MessageBody class. To maximize flexibility I opted to handle my own serialization. So MessageMapper utilized the BodyStream properties on the message. The MessageMapper Body property appears below.

MessageQueueMediator handles MessageQueues on behalf of the MSMQGateway. Typically a class like MessageQueueMediator would be internal and therefore hidden inside an assembly. Somehow, a delegate processing a MessageBody class must indicate that the message has been successfully processed and the MessageQueueMediator can move on the next message. MessageQueueMediatorVisitor packages the MessageBody class and controls access to the MessageQueueMediator class.

As you can see in the code below, the MessageQueueMediatorVisitor's CompleteReceive function indicates to the MessageQueueMediator that the message has been processed. MessageQueueMediator calls the MessageQueue class's Receive function and then starts another Peek.