【问题标题】:C# Cross-thread operation not valid [duplicate]C#跨线程操作无效[重复]
【发布时间】:2011-07-11 11:28:24
【问题描述】:

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

我收到一条错误消息 - 谁能给我一些指示。

跨线程操作无效:从 a 访问的控件“pbx_1” 线程不是创建它的线程。

我看过这里,但我似乎无法让它工作。我对 c# 很陌生,所以我可能遗漏了一些东西。

 Console.WriteLine("backgroundWorker1");
 while (!backgroundWorker1.CancellationPending) {
     Thread.Sleep(100);
     if (pbx_1.Location.X < Click_X) {
         pbx_1.Location = new Point(20, pbx_1.Location.X + MoveAmt);
     }

     if (pbx_1.Location.X > Click_X) {
         pbx_1.Location = new Point(20, pbx_1.Location.X - MoveAmt);
     }

     backgroundWorker1.ReportProgress(1);
 }

【问题讨论】:

  • 您是否尝试在 google 和/或 stackoverflow 上搜索此内容?

标签: c# multithreading


【解决方案1】:

你应该调用backgroundWorker1.ReportProgress(1);,因为只有 UI 线程可以直接访问 UI 控件。调用示例:

private delegate void AddListBoxItemDelegate(object item);

private void AddListBoxItem(object item)
{
   if (this.listBox1.InvokeRequired)
   {
       // This is a worker thread so delegate the task.
       this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
   }
   else
   {
       // This is the UI thread so perform the task.
       this.listBox1.Items.Add(item);
   }
}

【讨论】:

  • 挤点或链接重复...我知道你去了哪里Link 1; Link 2; Link 3; Link4
  • 链接 1 工作 - 感谢体育 - 不确定 Milk 积分是什么意思,但对于任何混淆感到抱歉。对其他人 - 抱歉 - 线程标记为删除 - 道歉。 if (pbx_1.Location.X
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
相关资源
最近更新 更多