The call thread cannot access this object because it belongs to a different thread

Asked

Viewed 2,182 times

4

Follows 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 mistake I get:

System.Invalidoperationexception: 'The call thread cannot access this object because it belongs to a different thread.'

This mistake happens only inside ConnectionReceived, if I put the line button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent)); outside the ConnectionReceived works normal.

Some solution ?

1 answer

4


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 use the Dispatcher. Example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.