Search code examples
c#eventhandler

C# Event Handler Issue Updating Control


So, here is the layout:

frmClient = uses frmLogin (LoginWindow) which has OnLoginEvent

this event is received by frmClient, and will update the statusbar (doesn't have invoke)

frmClient also uses ClassMatrix (Matrix) which has OnClientConnectEvent, which is invoked by ClassServer's event

frmClient is receiving the event from Matrix <- ClassServer

but it is showing multithreading error when trying to update statusbar

frmClient <- frmLogin's event works to update
frmClient <- Matrix <- Server's event errors with multithread

Server:

public event EventHandler<string> OnConnectionAcceptedEvent;
protected virtual void ConnectionAccepted(string e) { OnConnectionAcceptedEvent?.Invoke(this, e); }

server

Task.Run(new Action(async() =>.....
                        Client = new TcpClient("127.0.0.1", Port);

                        if (ID == 9999)
                        {

                            Guid _guid = Guid.NewGuid();
                            StageOneReaderServerStarted(ID.ToString());
                            ConnectionAccepted(ID.ToString()); // This is the command

                            GuidCreated(_guid.ToString());

                            SentGuid(_guid.ToString());

                            StartedStandardEncryption(ID.ToString());

                            StageTwoReaderServerStarted(ID.ToString());
                       }


    

Matrix:

public event EventHandler<string> ConnectionUpdateEvent;


Servers.Servers[Servers.Servers.FindIndex(f => f.ID == id)].OnConnectionAcceptedEvent += Matrix_OnConnectionAcceptedEvent;


private void Matrix_OnConnectionAcceptedEvent(object sender, string e)
{
    ConnectionUpdateEvent?.Invoke(this, e);
    Console.WriteLine($"Connection Accepted: {e}");
}

Client:

Matrix.ConnectionUpdateEvent += Matrix_ConnectionUpdateEvent;
LoginWindow.OnLogin += LoginWindow_OnLoginEvent;

protected virtual Matrix_ConnectionUpdateEvent(object sender, string e)
{
    statusPanel.Text = "Loggiasfasfasfng in..."; //works
}

protected virtual void LoginWindow_OnLoginEvent(object sender, string data)
{
    statusPanel.Text = "Logging in..."; //works
    Matrix.SentLogin(data);
}

Solution

  • So, apparently statusbars have .Parent.Invoke / .Parent/InvokeRequired

    this works now, took me forever to figure it out

     if (statusPanel.Parent.InvokeRequired)
     {
         statusPanel.Parent.Invoke(new MethodInvoker(delegate { statusPanel.Text = "fffff"; }));
     }