Search code examples
c#rabbitmqeasynetq

C# Many onMessage actions in EasyNetQ


I have a question. I have a simple method that creates subscription to RabbitMQ bus and read messages from it and then fires proper onMessage Action handler and it looks like:

    this.bus = RabbitHutch.CreateBus("host=localhost;timeout=999;virtualHost=/;username=guest;password=guest");

    void timer1_Tick(object sender, EventArgs e)
    {
       Console.WriteLine($"{DateTime.Now}");
    }

    var subscribeId = "QueueId";
    var running = false;
    var handler = new Action<ResponseMessage>(response =>
    {
        switch (response.Op)
        {
            case "Start":
                timer.AutoReset = true; 
                timer.Elapsed += timer1_Tick;
                timer.Start();
                break;
            default: Console.WriteLine("Default");
                break;
        }
    });

    this.bus.Subscribe<ResponseMessage>(cabinetSubscribeId, handler, sub => sub.WithTopic(cabinetSubscribeId));

Well it works fine when this will recive one message, but if the other come with Op value start (and this could happen) i am having 2 handlers running next to each other, and they will increment with each incoming start message.

Is it possible to stop previous onMessage handler, or limit those only to 1?


Solution

  • Every time message arrives you execute:

     case "Start":
                    timer.AutoReset = true; 
                    timer.Elapsed += timer1_Tick;
                    timer.Start();
                    break;
    

    You create additional subscription to timer. So timer now will call time_click1 twice. It is not clear why you need a timer at all here, but if you need then you need to unsubscribe from the previous first, also it should be thread sage, so put lock statment around this code

     case "Start":
                    timer.AutoReset = true; 
                    timer.Elapsed -= timer1_Tick;
                    timer.Elapsed += timer1_Tick;
                    timer.Start();