I am trying to create a console application that listens to a Message queue on my local computer. this is my code so far..
static void Main(string[] args)
{
var _queue = new MessageQueue(@".\private$\testing");
_queue.Formatter = new XmlMessageFormatter(new Type[] {
typeof(string) });
_queue.ReceiveCompleted += new
ReceiveCompletedEventHandler(queue_ReceiveCompleted);
_queue.BeginReceive();
}
private static void queue_ReceiveCompleted(object source,
ReceiveCompletedEventArgs e)
{
MessageQueue mq = (MessageQueue)source;
Message msg = mq.EndReceive(e.AsyncResult);
Console.WriteLine(msg.Body.ToString());
mq.BeginReceive();
}
my problem is like this.. First of all the program exits right after
Console.WriteLine(msg.Body.ToString());
and I don't get the other messages in the queue.
So I tried without Console.WriteLine to see if all messages are read from the queue
private static void queue_ReceiveCompleted(object source,
ReceiveCompletedEventArgs e)
{
MessageQueue mq = (MessageQueue)source;
Message msg = mq.EndReceive(e.AsyncResult);
mq.BeginReceive();
}
but then the results were inconsistent some times it would read 1 message some times 4 and sometimes all.
so whats going on, am I doing anything wrong?
The BeginReceive
method is asynchronous, so it will not prevent the main()
to exit.
What you can do is just add a Console.ReadKey();
at the end of the main()
to prevent this, until user interact.