【问题标题】:Cross-thread operation not valid: Control 'listBox1' accessed from a > thread other than the thread it was created on [duplicate]跨线程操作无效:控件'listBox1'从一个>线程访问,而不是它在[重复]上创建的线程
【发布时间】:2011-10-05 04:03:52
【问题描述】:

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

当我尝试将项目添加到 ListBox 时,我收到以下错误:

跨线程操作无效:从 a 访问的控件“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# 和线程方面有点新手,我用谷歌搜索并查看了许多文章,包括 SO,但我仍然不知道如何解决问题。

【问题讨论】:

  • 如果你看这个页面的右边,有几十个关于同一主题的问题。我刚选了最上面的那个。

标签: c# xmpp multithreading


【解决方案1】:

试试这个

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

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

   }));
}

【讨论】:

    【解决方案2】:

    除了 ui 线程之外,您不能触摸任何其他线程上的 ui 控件。当您收到错误时,将在单独的线程上调用 OnPresence 处理程序。您需要使用 Invoke() 或 BeginInvoke() 在 ui 线程上进行 listbox.Items.Add 调用,参见例如 http://weblogs.asp.net/justin_rogers/pages/126345.aspx

    【讨论】:

    • 谢谢安德斯,@Henk,先生,我检查了一些,但专业人士总是以严格的方式回答,所以 icnt 抓住它。感谢您的建议,我会检查。
    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2011-01-15
    • 2016-05-21
    • 2016-06-11
    • 2015-05-14
    相关资源
    最近更新 更多