与Console.ReadLine()

时间:2016-05-12 16:14:21

标签: c# events rabbitmq listener console.readline

下面的程序基本上是来自C#Rabbit MQ Tutorial的Receiver / Worker程序中的程序:https://www.rabbitmq.com/tutorials/tutorial-two-dotnet.html(添加了一个计数器)。

有两三件事让我难过:

1)如果我注释掉“Console.ReadLine()”,它会消耗来自队列的消息并显示:

Start 
Press [enter] to exit. 
My End - CountMessagesProcessed=0

我测试的前几次,我无法弄清楚发生了什么。

2)此行永远不会出现在输出中:Console.WriteLine(“按[enter]退出。”);.大概是因为它在“Console.ReadLine();”之前,但为什么呢? ReadLine事件和BasicConsumer之间的相互作用是什么?

3)MQ Tutorial页面说使用CNTL-C来停止“监听器”进程,但我发现只需按Enter键就可以了。

之前我已经为MQSeries编写过监听程序,使用了线程,我可能会更喜欢,但只是想了解所提供的基本教程。

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);

            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

Console.ReadLine()在等待输入时停止执行您的程序,这允许RabbitMQ正在使用的线程同时运行。注释掉,程序执行运行到最后并退出,包括RabbitMQ线程。

是的,您可以键入任何内容,它将停止执行该程序;一旦你按下键,程序执行将继续并运行到最后。

答案 1 :(得分:0)

不要使用 Console.ReadLine(),而是使用 Thread.Sleep(Timeout.Infinite),这样您的主程序(或主线程)不会立即退出。它也适用于在 Linux 上运行 netcore rabbitmq。