Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a thread being completed in C#?

I have a RabbitMQ client program written in C#. While the application works in console based application (because execution is blocked by Console.ReadLine) it does not work in Windows Form based application. In Windows Form application, execution doesn't wait on Console.ReadLine and terminates on completion. I am looking for solution where my listener keeps monitoring for new messages from server without being terminated. Here is the the client code :

    try {
            var factory = new ConnectionFactory() { HostName = "xxx" , UserName ="xxx", Password="xxx"};
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: "call_notify",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(message);
                };
                channel.BasicConsume(queue: queueName,
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();  // Program does'nt wait here in windows form based application
            }
        }
like image 464
Faiz Avatar asked Sep 16 '25 03:09

Faiz


1 Answers

  1. Don't use using since that will dispose of everything immediately
  2. Store the needed objects (connection? channel? consumer?) in class fields rather than local variables
  3. No need for threads since the objects handle things asynchronously. Just create the objects and that's it
  4. Close/dispose of the objects when the application terminates or you need to stop listening

This way they'll live until the application terminates.

like image 78
Sami Kuhmonen Avatar answered Sep 17 '25 18:09

Sami Kuhmonen