我正在尝试在一个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被解雇了......有人遇到过类似的问题吗?据我所知,渠道创建是正常的
谢谢
1条答案
按热度按时间8mmmxcuj1#
当函数
InitializeAsync
完成时,连接和通道将被释放。您应该让它们保持活动状态。一种选择是将它们作为属性添加,并在InitializeAsync
中分配它们。