Whats the best way to get all the messages currently on a queue to process?
We have a queue with a large number of very small messages, what I would like to do is read all the current messages off and then send them through a thread pool for processing.
I can't seem to find any good resource which will show me how i can create a simple method to return an IEnnumerable for example
Thanks
Default is c:\windows\system32\msmq\.
Multiple tasks can send messages to a message queue; a sending task can be blocked when the target message queue is full. A message queue can also have multiple tasks receiving messages from it; a receiving task can be blocked when the queue is empty.
As a Windows component, MSMQ is technically “supported” as long as it's carried by a supported version of Windows. Since it exists in Windows 10 and Windows Server 2019, MSMQ will continue to live on until at least 2029—and much longer assuming it isn't removed from future versions of Windows.
Although I agree with Nick that the queue's purpose is more for FIFO style processing, and ArsenMkrt's solution will work, another option involves using a MessageEnumerator and piling the messages into your IEnumerable.
var msgEnumerator = queue.GetMessageEnumerator2();
var messages = new List<System.Messaging.Message>();
while (msgEnumerator.MoveNext(new TimeSpan(0, 0, 1)))
{
var msg = queue.ReceiveById(msgEnumerator.Current.Id, new TimeSpan(0, 0, 1));
messages.Add(msg);
}
For simple stuff...
public void DoIt()
{
bool continueToSeekForMessages = true;
while (continueToSeekForMessages)
{
try
{
var messageQueue = new System.Messaging.MessageQueue(@"FormatName:Direct=OS:MyComputerNameHere\Private$\MyPrivateQueueNameHere");
var message = messageQueue.Receive(new TimeSpan(0, 0, 3));
message.Formatter = new System.Messaging.XmlMessageFormatter(new String[] { "System.String,mscorlib" });
var messageBody = message.Body;
}
catch (Exception ex)
{
continueToSeekForMessages = false;
}
}
}
.
Also, could use peek instead of taking the message off the queue.
Also, could use GetMessageEnumerator2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With