Implementing Queue Storage
Queue storage is probably the easiest part to implement. Unlike Table storage, there is no need to setup a model and context, and unlike Blob storage, there is no need to be concerned with blocks and pages. Queue storage is only meant to store small messages, 8 KB or less. Adding a message to a Queue follows the same pattern as the other storage mechanisms. First, get a reference to the Queue, creating it if necessary, then add the message.
Hide Copy Code
public void Add(CloudQueueMessage msg)
{
Queue.AddMessage(msg);
}
Retrieving a message from the Queue is just as easy.
Hide Copy Code
public CloudQueueMessage GetNextMessage()
{
return Queue.PeekMessage() != null ? Queue.GetMessage() : null;
}
One thing to understand about Azure Queues is they are not like other types of Queues you may be familiar with, such as MSMQ. When a message is retrieved from the Queue, as above, it is not removed from it. The message will remain in the queue however Windows Azure will set a flag marking it as invisible to other requests. If the message has not been deleted from the Queue within a period of time, the default is 30 seconds, it will again be visible to
GetMessage
calls. This behavior also makes Windows Azure Queues non-FIFO as expected from other implementations.
At some point, you may want get all messages in a Queue. Although the
GetMessages
method will work for this, however, there are definitely some issues to be aware of. GetMessages
takes a parameter specifying the number of messages to return. Specifying a number greater than the number of messages in the Queue will produce andException
so you need to know how many messages are in the QUeue to retrieve. Because of the dynamic nature of Queues as explained above, the best Windows Azure can do is give an approximate count though. TheCloudQueue.ApproximateMessageCount
property would seem to be perfect for this. Unfortunately though, this property seems to always return null
. To get the count, you need to use theQueue.RetrieveApproximateMessageCount()
method.
Hide Copy Code
public static List<CloudQueueMessage> GetAllMessages()
{
// If the number requested is greater than the actual
// number of messages in the queue this will fail.
// So get the approximate number of messages available
// Although this would seem to a good property to use
// it will always return null
//int? count = Queue.ApproximateMessageCount;
// To get the count use this method
int count = Queue.RetrieveApproximateMessageCount();
return Queue.GetMessages(count).ToList();
}