Developr
Developr

Reputation: 447

Event handler not firing on class method

I have an event handler in a class which doesnt seem to trigger. I wonder if anyone had any ideas on why this may be happening (or not happening as is the case).

The class inherits from another class and basically listens for messages from a message queue. When a message hits the queue the method onMessage() is called.

From my (winforms, c#, .net 3.5) UI form, I'm trying to get the received message(s) back to the UI.

If I call the method onMessage() manually from the instance on my form, the eventhandler does trigger correctly and passMessage is executed on my UI form.

But when I receive a message thats come automated from the queue I'm listening on, the event handler is not triggered. I dont ever call the onMessage() method, that happens automatically.

Does anyone have any ideas why the event handler is not triggering when onMessage() is called everytime I receive a message?

Thanks

UI:

private void btnConnect(object sender, EventArgs e)
{
    MessageQueue myMQ = new MessageQueue();
    myMQ.Connect(...);
    //Register handler
        myMQ.MsgTrigger += new EventHandler(passMessage);
}

public void passMessage(object s, EventArgs e)
{
    Console.WriteLine(s.ToString()); //Not sure if this is a good way to pass back a value
}

Class:

namespace MQListener
{
    class MessageQueue : MQ.MessageListener
    {
        public event EventHandler MsgTrigger;

        public virtual void onMessage(MQ.Message Message)
        {
            MQ.TextMessage txtMessage = (MQ.TextMessage)Message;
            String MsgBody = txtMessage.getMessage();
            Console.WriteLine(MsgBody);

            object objMsg = (object)MsgBody;

            var _Trigger = MsgTrigger;

                if(_Trigger != null)
                   _Trigger(objMsg, null);
        }
    }
}

Upvotes: 1

Views: 10506

Answers (1)

Slippery Pete
Slippery Pete

Reputation: 3110

  1. Your event subscription should happen before you connect:

    private void btnConnect(object sender, EventArgs e)
    {
        MessageQueue myMQ = new MessageQueue();
        //Register handler
        myMQ.MsgTrigger += new EventHandler(passMessage);
        myMQ.Connect(...);
    }
    
  2. You can only update controls from the UI thread, so to prevent the error "'txtMessage' accessed from a thread other than the thread it was created on.", you need to check the control's InvokeRequired property. If true, you need to call the Invoke() method. See this SO question: Automating the InvokeRequired code pattern

Upvotes: 1

Related Questions