I'm trying to implement an WinForm RabbitMQ client, in which I'm receiving message from the server as follows-
private void Form1_Load(object sender, System.EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var factory = new ConnectionFactory() { HostName = "192.168.100.6", Password = "pass", UserName = "username" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("CallCenter", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("CallCenter", true, consumer);
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
MessageBox.Show(message);
}
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.Dispose();
}
I'm pretty sure it's not a good approach. Rather, It would be better if there is an OnMessageReceived
event.
Do you have any good example about event-based message receiving in RabbiMQ?
The way you're doing it is correct. consumer.Queue.Dequeue();
is essentially an OnMessageReceived, it is a blocking call that sits and waits for messages to be sent to it from rabbit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.