WPF(winform)使用MassTransit组件正确消费RabbitMQ队列的正确姿势。
可更新UI页面,自动通知。
思路:传统实现消费IConsumer接口,采用new窗体来消费。
关键代码:
var win2 = new Window1();
cfg.ReceiveEndpoint(host, "customer_update_queue", e =>
{
//e.Consumer(() => win2);
e.Consumer<UpdateCustomerConsumer>(win2);
});
代码示意,没有真实环境
--实例化bus及消费者
private void button_Click(object sender, RoutedEventArgs e)
{
var host = cfg.Host(new Uri("rabbitmq://localhost/"));
var win2 = new Window1();
cfg.ReceiveEndpoint(host, "customer_update_queue", e =>
{
//e.Consumer(() => win2);
e.Consumer<UpdateCustomerConsumer>(win2);
});
busControl.Start();
win2.Show();
}
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window,IConsumer<UpdateCustomerAddress>
{
public Window1()
{
InitializeComponent();
}
public void updatevalue(string id, int v)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { label.Content = id; progressBar1.Value = v; }));
}
//自动接收消息,因为不在同一线程中,需要特殊处理UI页面。
public async Task Consume(ConsumeContext<UpdateCustomerAddress> context)
{
updatevalue(context.Message.CustomerId, 50);
return Task.FromResult(1);
}
}
}