0

I have a queue of messages that I would like to read. Consider the following code, based on a queue of 100 items:

queue.FetchAttributes();
            var orderCount = queue.ApproximateMessageCount;
            while(orderCount > 0)
            {
                var messages = queue.GetMessages(32,TimeSpan.FromMinutes(1));
                if (messages != null)
                {
                    foreach (var item in messages)
                    {
                        Order singleOrder = new JavaScriptSerializer().Deserialize<Order>(item.AsString);
                        PendingOrders.Add(singleOrder);
                    }
                }
                queue.FetchAttributes();
                orderCount = (messages == null) ? 0 : queue.ApproximateMessageCount;
            }

In this instance, 3 calls will be made to "queue.GetMessages()" to retrieve 96 messages, followed by a 4th call to get the remaining 4. The loop will then exit and the list of items returned. When I run this, it appears to be lifting the same items over and over i.e. not incrementing. I was under the impression when I read an item, it removed it from the queue temporarily? So each time I read a message, it gets temporarily removed from my queue - in this case for 1 minute. Have I missed a step? Note, I am not calling 'DeQueue' anywhere as I want the item to return to the queue after 1 minute.

Adrian
  • 670
  • 10
  • 24

1 Answers1

0

When you call queue.GetMessages, you're actually performing a Dequeue operation on your queue. GetMessages operation actually makes the messages fetched invisible for a duration of 1 minute.

However the messages are not removed from the queue. So when you call queue.FetchAttributes() which populates ApproximateMessageCount property of the queue will always return the same number (100). Thus depending on how much time you spend in executing PendingOrders.Add(singleOrder); line of code, it is entirely possible that you get the same messages back. If it takes more than a minute to loop over 32 messages, then these messages become visible again (enqueued in other words) and in the next iteration you get the same messages back.

Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241