The program below is basically the program from Receiver/Worker program from the C# Rabbit MQ Tutorial here: https://www.rabbitmq.com/tutorials/tutorial-two-dotnet.html (with a counter added).
There are two or three things that have me stumped about it:
1) If I comment out the "Console.ReadLine()" it consumes the messages from the Queue and displays:
Start Press [enter] to exit. My End - CountMessagesProcessed=0
The first few times I was testing, I couldn't figure out what was going on.
2) This line never shows up in the output: Console.WriteLine(" Press [enter] to exit.");. Presumably because it's before the "Console.ReadLine();", but why? What is the interplay between the ReadLine event and the BasicConsumer?
3) The MQ Tutorial page says to use CNTL-C to stop the "listener" process, but I find that just pressing enter works equally well.
I've written listeners for MQSeries before, with threading, which I might like better, but just trying to understand the basic tutorials provided.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitMQReceiver
{
class Receive
{
public static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
var myQueuename = "MyQueueName1";
Console.WriteLine("My Start");
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: myQueuename,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
int countMessagesProcessed = 0;
// this chunk of code is passed as parm/variable to BasicConsume Method below to process each item pulled of the Queue
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
countMessagesProcessed++;
Console.WriteLine(" [x] Received {0}", message);
}
channel.BasicConsume(queue: myQueuename,
noAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit."); // this line never shows up in output
Console.ReadLine(); // if this line is commented out the message are consumed, but no Console.WriteLines appear at all.
Console.WriteLine("My End - CountMessagesProcessed=" + countMessagesProcessed);
}
}
}
}