rafaelsilva
rafaelsilva

Reputation: 3

Best approach to read messages in a queue in rabbitmq in c#

I'm starting to learn RabbitMQ. I found some internet tutorials about how to consume a message of a queue. But I would like to know how best approach for this. Today I'm using a simple code inside a timer that return a message if exists and do some work. Other example is using while true loop like code below. Is exists some feature in rabbitmq to register a method callback that fire when a message is published in a specific queue? I wouldn't like to check if exists and get messages inside the while true loop if there are other way for this. Thanks.

var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare("hello", false, false, false, null);

        var consumer = new QueueingBasicConsumer(channel);
        channel.BasicConsume("hello", true, consumer);

        Console.WriteLine(" [*] Waiting for messages." +
                                 "To exit press CTRL+C");
        while (true)
        {
            var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

            var body = ea.Body;
            var message = Encoding.UTF8.GetString(body);
            Console.WriteLine(" [x] Received {0}", message);
        }
    }
}

Upvotes: 0

Views: 9786

Answers (1)

theMayer
theMayer

Reputation: 16177

I believe that what you are looking for is the EventingBasicConsumer. Under the hood, what this consumer does is operate a background thread that runs a loop, inserting any messages into a temporary blocking queue. Then, a separate thread dispatches each message from the blocking queue as an event to the consumer.

See the .net API guide for more details.

Upvotes: 1

Related Questions