I have a Windows service using NServiceBus to handle incoming messages. While processing a message, I would like to check to see if there are any other remaining messages on the queue to process. What is the best way to approach this?
1
votes
Scott out of curiosity why do you care if other messages are on the queue?
– tom redfern
I have a handler that converts the messages into rows of a spreadsheet, for uploading into a legacy system. (one message = one row). I don't want to move the spreadsheet to the upload folder until there are no more messages on the queue. i.e. I want to upload a single big spreadsheet, not 1000's of 1 row spreadsheets.
– Scott Ferguson
Another way to handle this would be to "ticket" each message for example 1 of 10, 2 of 10 etc. This would obviously have to be done on the sender's side.
– tom redfern
thanks hugh, but in this case there are multiple senders, each unaware of each other. Appreciate your suggestion though.
– Scott Ferguson
2 Answers
4
votes
For this specific scenario I'd say that a saga could be appropriate where it is created by the first message received, opens a timeout (for let's say one minute), collects all messages during that period of time, then Bus.SendLocal's a message containing all rows, for which another handler creates the spreadsheet and uploads.
1
votes
Since, NServiceBus
is using MSMQ
, you can use the methods from System.Messaging
.
Included is a modified method, I'm currently working on, to do a kind of batch processing.
using System.Messaging;
public int PeekAtQueue()
{
const string QUEUE_NAME = "private$\\you_precious_queuname";
if (!MessageQueue.Exists(".\\" + QUEUE_NAME))
return 0;
var messageQueues = MessageQueue.GetPrivateQueuesByMachine(Environment.MachineName);
var queue = messageQueues.Single(x => x.QueueName == QUEUE_NAME);
return queue.GetAllMessages().Count();
}
Modified here itself in the editor. Hope it still compiles :) Found a similar discussion here, by the way:
http://jopinblog.wordpress.com/2008/03/12/counting-messages-in-an-msmq-messagequeue-from-c/