❔ c# wpf textbox access violation

Hello does anyone know how can i edit the TextBox1.Text within the Task.run so i don't have an access violation ? here is the code :
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80));
Server.Listen(2);

Socket Client;

await Task.Run(() =>
{
Client = Server.Accept();
TextBox1.Text = "Hello";

});
}

catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80));
Server.Listen(2);

Socket Client;

await Task.Run(() =>
{
Client = Server.Accept();
TextBox1.Text = "Hello";

});
}

catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
}
}
3 Replies
reflectronic
reflectronic2y ago
you can only edit the control on the UI thread, the Task.Run takes you to a different thread so it won't work. you can "come back" to the UI thread temporarily with Dispatcher.Invoke
await Task.Run(() =>
{
Client = Server.Accept();
Dispatcher.Invoke(() =>
{
TextBox1.Text = "Hello";
}
}
await Task.Run(() =>
{
Client = Server.Accept();
Dispatcher.Invoke(() =>
{
TextBox1.Text = "Hello";
}
}
(though, if i may, i would suggest:)
await Task.Run(async () =>
{
Client = await Server.AcceptAsync();
Dispatcher.Invoke(() =>
{
TextBox1.Text = "Hello";
}
}
await Task.Run(async () =>
{
Client = await Server.AcceptAsync();
Dispatcher.Invoke(() =>
{
TextBox1.Text = "Hello";
}
}
MotherBroker
MotherBrokerOP2y ago
Thanks it worked
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server