When to Wait for Messages
When you call receive on a channel, there is always a timeout that bounds that receive operation. There are actually three different kinds of receive on the standard input channel shape. The Receive method waits for a message to arrive up to the timeout period and then throws an exception if no message actually comes. Most of the time, this receive behavior is what you want to build around. Give Receive as much time as you can afford and then simply fail if no messages show up.
The second kind of receive, TryReceive, is similar to the standard Receive but with a soft failure mode. Instead of indicating the failure to receive through an exception, TryReceive has a boolean return value that indicates whether the operation succeeded. A successful attempt to receive provides you with the message as normal. If you can't effectively recover from a lack of messages, then you should probably be using the basic Receive. If there is some way for you to recover, then TryReceive allows you to avoid the expense of throwing and catching the TimeoutException.
The final type of receive, WaitForMessage, is essentially a peek operation. Like TryReceive, WaitForMessage uses a boolean return value to indicate whether the operation succeeded. However, WaitForMessage never returns a message to you. It simply says that if you had actually performed a Receive operation, then you would have seen a message arrive before the timeout expired. Waiting for a message can be used to defer work until a message is ready for processing. One example of this type of work deferment is the receipt of a message inside of a transaction. Suppose that you had a loop checking for messages to arrive. If you just called Receive or TryReceive, then you would need to start a transaction every time through the loop in case a message showed up. Each time a receive attempt failed, the transaction would have to be canceled. With WaitForMessage, you could instead peek for messages and then only start a transaction when you knew that a message was likely to be there.
Next time: Handling Message Encoder Errors