Question :
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?
Answer :
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));
);