Cross-thread operation not valid

R

Raj

I have .net 3.5 window application having a combobox. While running the
client/server I got this error

Cross-thread operation not valid: Control 'comboBox1' accessed from a thread
other than the thread it was created on.

private void Form1_Load(object sender, EventArgs e)
{
Thread theudpserver = new Thread(new ThreadStart(ServerThread));
theudpserver.Start();
}


public void ServerThread()
{
UdpClient udpclient = new UdpClient(8080);
while (true)
{
IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any,
0);
Byte[] receivebytes = udpclient.Receive(ref remoteipendpoint);
string returndata = Encoding.ASCII.GetString(receivebytes);
comboBox1.Items.Add(remoteipendpoint.Address.ToString() +
":" + returndata.ToString());
}
}

Any help would be appreciated.

Thank you

Regards
Raj
 
W

Willem van Rumpt

Raj said:
I have .net 3.5 window application having a combobox. While running the
client/server I got this error

Cross-thread operation not valid: Control 'comboBox1' accessed from a thread
other than the thread it was created on.

private void Form1_Load(object sender, EventArgs e)
{
Thread theudpserver = new Thread(new ThreadStart(ServerThread));
theudpserver.Start();
}


public void ServerThread()
{
UdpClient udpclient = new UdpClient(8080);
while (true)
{
IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any,
0);
Byte[] receivebytes = udpclient.Receive(ref remoteipendpoint);
string returndata = Encoding.ASCII.GetString(receivebytes);
comboBox1.Items.Add(remoteipendpoint.Address.ToString() +
":" + returndata.ToString());
}
}

Any help would be appreciated.

Well, the exception tells you /exactly/ what is wrong. You're accessing
the combobox from within another thread (the "theudpserver" thread in
this case).

Controls in winforms application are bound to a thread, and not
threadsafe. You can use Control.Invoke (or the asynchronous Begin- /
EndInvoke pair) to marshal the call to the UI thread.

see also:

http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top