kleineLotti kleineLotti - 4 years ago 241
C# Question

RabbitMQ Consumer always directly shutsdown (C#)

At The moment im learning how to work with the RabbitMQ.
Sending works. But Recieving doesn't work. This is my code:

var factory = new ConnectionFactory() { HostName = hostName };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: queueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Recieved: {0}", message);
};
consumer.Shutdown += (o, e) =>
{
Console.WriteLine("Error with RabbitMQ: {0}", e.Cause);
createConnection(hostName, queueName);
};
channel.BasicConsume(queueName, true, consumer);
}


This is copied from the Tutorial. If I start the Application, consumer.Shutdown is directly called and I get:

{AMQP close-reason, initiated by Application, code=200, text="Goodbye", classId=0, methodId=0, cause=}


Can anyone help me?

Evk Evk
Answer Source

channel.BasicConsume is non-blocking call, which means it will return immediately. What happens next in your example is your channel and connection are getting disposed (because of using statement), and so you see immediate shutdown. In the example you copied this code from, there is Console.ReadLine statement right after channel.BasicConsume. This prevents channel and connection from disposing until user press key in console.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download