gpt4 book ai didi

c# - 与 Console.ReadLine() 相关的 RabbitMQ BasicConsume 和事件驱动问题

转载 作者:行者123 更新时间:2023-11-30 17:37:59 25 4
gpt4 key购买 nike

下面的程序基本上是 C# Rabbit MQ 教程中 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("Press [enter] to exit.");。大概是因为它在“Console.ReadLine();”之前,但为什么呢? ReadLine 事件和 BasicConsumer 之间的相互作用是什么?

3) MQ 教程页面说使用 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);

}
}
}
}

最佳答案

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

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

关于c# - 与 Console.ReadLine() 相关的 RabbitMQ BasicConsume 和事件驱动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com