跨线程操作无效:从访问控制“listBox1中”>线程以外它是在创建线程[重复]

问题描述 投票:4回答:2

可能重复: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

当我试图将项目添加到列表框,我'得到以下错误:

跨线程操作无效:控制“listBox1中”从比它创建的线程以外的线程访问。

下面是试图代码:

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

我在C#有点新的,也有穿的,我用Google搜索和检查过很多文章,包括SO,但我仍然不知道如何解决这个问题。

c# xmpp multithreading
2个回答
13
投票

尝试了这一点

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

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

   }));
}

1
投票

你可以不触及任何其他线程比UI线程的UI控件。当你错误的OnPresence处理程序被称为一个单独的线程。你需要做的listbox.Items.Add通话发生在UI线程上,使用的invoke()或BeginInvoke的(),见例如http://weblogs.asp.net/justin_rogers/pages/126345.aspx

© www.soinside.com 2019 - 2024. All rights reserved.