RabbitMQ示例在WPF中不工作

11dmarpk  于 2022-11-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(223)

我正在尝试在一个WPF应用程序下使用rabbitMQ。我已经按照rabbitmq站点上的示例进行了操作。
发送程序是一个控制台应用程序,

static void Main(string[] args)
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };

        using (var connection = factory.CreateConnection())
        {

                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello",
                        durable: false,
                        exclusive: false,
                        autoDelete: false,
                        arguments: null);

                    string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                        routingKey: "hello",
                        basicProperties: null,
                        body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }

    }

主窗口视图模型

public class MainWindowViewModel :ViewModelBase
{
    protected override Task InitializeAsync()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Registered += Consumer_Registered;
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

        }

        return base.InitializeAsync();
    }

    private void Consumer_Registered(object sender, ConsumerEventArgs e)
    {
        int t = 0;
    }
}

这段代码在wpf上不起作用。同样的代码放在控制台应用程序中也能起作用
我注意到Consumer_Registered被解雇了......有人遇到过类似的问题吗?据我所知,渠道创建是正常的
谢谢

8mmmxcuj

8mmmxcuj1#

当函数InitializeAsync完成时,连接和通道将被释放。您应该让它们保持活动状态。一种选择是将它们作为属性添加,并在InitializeAsync中分配它们。

相关问题