Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-thread operation not valid: Control 'listBox1' accessed from a > thread other than the thread it was created on [duplicate]

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

While I am trying to add items to a ListBox, I'am getting the following error:

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

Here is tried code:

private void Form1_Load(object sender, EventArgs e)
{
    Jid jd = new Jid("USERNAME");
    xmpp.Open(jd.User, "PASSWORD");
    xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
    agsXMPP.XmppConnection p;
    xmpp.OnPresence += new PresenceHandler(xmpp_OnPresence);
}
void xmpp_OnPresence(object sender, Presence pres)
{
    listBox1.Items.Add(pres.From .User ); --- **HERE I AM GETTING ERROR.**
}

I am little bit new in C# and also with threading, I googled and checked many articles including SO, But still I don't know how to solve the problem.

like image 851
Dileep DiL Avatar asked Jul 14 '11 09:07

Dileep DiL


2 Answers

Try this out

void xmpp_OnPresence(object sender, Presence pres)
    {
  this.Invoke(new MethodInvoker(delegate()
                {

listBox1.Items.Add(pres.From .User ); --- **HERE I AM GETTING ERROR.**

   }));
}
like image 98
Zain Ali Avatar answered Oct 18 '22 21:10

Zain Ali


You cannot touch the ui controls on any other thread than the ui thread. The OnPresence handler is called on a separate thread when you get the error. You need to make the listbox.Items.Add call happen on the ui thread, using Invoke() or BeginInvoke(), see for example http://weblogs.asp.net/justin_rogers/pages/126345.aspx

like image 42
Anders Forsgren Avatar answered Oct 18 '22 21:10

Anders Forsgren