Event subscribed but null in child class (after threads initialize)

140 views Asked by At

I went over this many times looking for what I could be doing wrong. Basically in my C# application I have a class that accepts a message from SignalR then fires an event with the message for any listeners. I've got many custom events working just fine and I've compared this code and it all seems fine.

In the messaging class I have this:

    private string _message = string.Empty;

    public event EventHandler evtNewMessage;

    public string szMessage
    {
        get { return this._message; }
        set
        {
            this._message = value;

            if (this.evtNewMessage != null)
                this.evtNewMessage(this, new EventArgs());
        }
    }

I've put a break on the line if (this.evtNewMessage) != null) and I can see that the message makes it there, but the "this.evtNewMessage" is always null so the line following "this.evtNewMessage(this, new EventArgs());" never runs.

I also verified the calling app...

public partial class TestFunc : Form
{
    ...
    sigClient oClient = new sigClient();

    public TestFunc()
    {
        oClient.evtNewMessage += EventHandler(DataReceived);
        oClient.Startup();
        Listen();
    }

    private void Listen()
    {
        oClient.RunTests();
    }

    private void DataReceived(object sender, EventArgs e)
    {
        //var receivedMessage = System.Text.Encoding.UTF8.GetString(e.Data);
        sigClient TempObj = (sigClient)sender;

        tbOutPut.Text += TempObj.szMessage;
    }

I set a break on the line "oClient.evtNewMessage += new EventHandler(DataReceived);" and I can see the event is null before and assigned after the line is run.

The function DataReceived never gets hit because the event is never fired; it thinks nothing has subscribed. I can break the execution at any point and I can see the event is assigned in the application. However, when I step into the child class, it shows the event as null/unassigned.

Anyone know what may be going on?

Edit: I set up another test where I initialize the comm class, subscribe, and send a test message before the threads initialize and it works. For some reason, the threads are overwriting the handler but it's not a static class so I'm not sure why that's happening?

0

There are 0 answers