【问题标题】:how to respond to an event on a different thread如何响应不同线程上的事件
【发布时间】:2018-07-09 07:37:25
【问题描述】:

我已经实现了一个 rabbitMQ 监听器,它本质上只是在一个循环中等待消息到达。当消息到达时,我希望触发一个事件并运行一些代码。

但是我似乎并不总是收到这个事件,我想知道这是否是因为我在不同的线程上运行队列轮询部分代码。

虽然它最初似乎确实有效,所以线程可能不是问题。谁能给我意见?

队列监听器:

 public void CreateQueueListener<T>() where T : IPubSubEvent
    {            

        var mqServer = new RabbitMqServer(m_RabbitMqAddress);
        var mqClient = (RabbitMqQueueClient)mqServer.MessageFactory.CreateMessageQueueClient();

        var channel = mqClient.Channel;
        string queueName = mqClient.GetTempQueueName();


        channel.QueueBind(queueName, m_EventExchange, routingKey: QueueNames<T>.In);

        var consumer = new RabbitMqBasicConsumer(channel);
        channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);
        Task.Run(() =>
        {
            while (true)
            {
                BasicGetResult basicGetResult;
                try
                {
                    basicGetResult = consumer.Queue.Dequeue();
                }

                catch (Exception ex)
                {
                    throw;
                }
                var message = basicGetResult.ToMessage<T>();
                PublishEvent?.Invoke(this, new PubSubEventArgs { EventData = message.GetBody().EventName });                    
            }
        });
    }

消费类

public class MyClass
{
 public MyClass(IEventClient eventClient)
    {
        eventClient.CreateQueueListener<AuthoriseEvent>();
        eventClient.PublishEvent += OnPublishEvent;
    }

    private async void OnPublishEvent(object sender, PubSubEventArgs e)
    {
        if (e.EventData == "AuthoriseEvent")
            //dostuff
    }
}

【问题讨论】:

    标签: c# multithreading rabbitmq


    【解决方案1】:

    我正在另一个线程上运行队列轮询部分代码

    据我所知,.NET 客户端不支持此功能。


    注意:RabbitMQ 团队监控the rabbitmq-users mailing list,并且有时只回答 StackOverflow 上的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2015-10-29
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多