-2

ErrorError

I don't know why to give me this error when Events_ClientConnected run give me this error and i search in the internet I didn't found anything this is my code :

        SimpleTcpServer server;
        public Main_Window()
        {
            InitializeComponent();
            server = new SimpleTcpServer(ip_txtbox.Text);
            server.Events.DataReceived += Events_DataReceived;
            server.Events.ClientConnected += Events_ClientConnected;
            server.Events.ClientDisconnected += Events_ClientDisconnected;
        }

        public void start_btn_Click(object sender, RoutedEventArgs e)
        {
                log_txtbox.Text += Environment.NewLine + "*Starting server*";
                server.Start();
                log_txtbox.Text += Environment.NewLine + "*Done*";
        }



        private void Events_ClientDisconnected(object sender, ClientDisconnectedEventArgs e)
        {
            log_txtbox.Text += Environment.NewLine + e.IpPort + "Quit";
        }

        private void Events_ClientConnected(object sender, ClientConnectedEventArgs e)
        {
            log_txtbox.Text += Environment.NewLine + e.IpPort +"Join";
        }

        private void Events_DataReceived(object sender, DataReceivedEventArgs e)
        {
            log_txtbox.Text += Environment.NewLine + e.IpPort +":"+ Encoding.UTF8.GetString(e.Data);
        }

        private void stop_btn_Click(object sender, RoutedEventArgs e)
        {
            server.Stop();
            log_txtbox.Text += Environment.NewLine + "*Server shutdown*";
        }
eskandari
  • 1
  • 1

1 Answers1

0

In WPF not everyone can change UI element. In this case the event is called on a thread who is not responsible of the UI stuff.

You have to call the dispatcher to modify UI like in this question : The calling thread cannot access this object because a different thread owns it

So it should probably be :

private void Events_ClientConnected(object sender, ClientConnectedEventArgs e)
{
    this.Dispatcher.Invoke(() => log_txtbox.Text += Environment.NewLine + e.IpPort +"Join");
}
Arcord
  • 1,724
  • 1
  • 11
  • 16