The calling thread can not access this object because it belongs to a different thread

3

Follow the code:

private async void button_1_Click(object sender, RoutedEventArgs e)
{    
    var listenPort = 11000;
    var listener = new TcpSocketListener();
    listener.ConnectionReceived += async (senders, args) =>
    {
        var client = args.SocketClient;
        var reader = new StreamReader(client.ReadStream);
        var data = await reader.ReadLineAsync() + "\n";

        var split = data.Split('#');

        button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

        var bytes = Encoding.UTF8.GetBytes(data);
        await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
        await client.WriteStream.FlushAsync();
    };

    await listener.StartListeningAsync(listenPort);
}

The error I get:

  

System.InvalidOperationException: 'The calling thread can not   access this object because it belongs to a different thread. '

This error happens only within ConnectionReceived , if I put the line button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent)); out of ConnectionReceived it works normal.

Any solution?

    
asked by anonymous 17.03.2018 / 00:32

1 answer

3

You have to access the interface components in the same thread where they were created (also known as the UI thread). To do this you can dispatcher . Example:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => 
    button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
);
    
17.03.2018 / 00:44