5

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.

Dileep DiL
  • 83
  • 1
  • 1
  • 6
  • If you look at the right of this page there are dozens of question about the same subject. I just picked the one on top . – H H Jul 14 '11 at 09:02

2 Answers2

13

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.**

   }));
}
Zain Ali
  • 15,535
  • 14
  • 95
  • 108
1

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

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
  • thank anders ,@Henk ,SIR ,I checked some ,but Professionals are always answering in a tight way ,so icnt catch it .thanks for the sugestion ,i will check. – Dileep DiL Jul 14 '11 at 09:14