开发者

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

开发者 https://www.devze.com 2023-03-20 10:04 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
This question already has answers here: Closed 11 years ago.

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.


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

   }));
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消