I am practicing on networking using c#, everything's great so far I had a situation with a client/serv app where i was trying to send and receive a message and add the message in a ListBox in the server app. But after sending the message from the client, it shows me an error (cross-thread operation not valid) and i can't add the message to the list from another Thread Here's the code :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread serverListen = new Thread(bufferHandlerThread);
serverListen.Start();
}
private void bufferHandlerThread()
{
UdpClient server = new UdpClient(6661);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = server.Receive(ref RemoteIpEndPoint);
string receivedData = Encoding.UTF8.GetString(buffer);
string toAdd = RemoteIpEndPoint.Address.ToString() " <-> " receivedData;
dataList.Items.Add(toAdd); // Here the exception.
}
}
}
Thank you :)
CodePudding user response:
Replace this:
dataList.Items.Add(toAdd);
With:
this.Invoke(() =>
{
dataList.Items.Add(toAdd);
});
CodePudding user response:
You can use the following methods.
public static void AddListItemThreadSafe<TControl>(this TControl @this, Action action) where TControl : ListBox
{
if (@this.InvokeRequired)
{
@this.Invoke((MethodInvoker)delegate
{
dataList.Items.Add(toAdd);
action();
});
}
else
{
action();
}
}