C#跨线程操作无效

本文关键字:无效 操作 线程 | 更新日期: 2023-09-27 18:01:39

可能重复:
跨线程操作无效:从创建控件的线程以外的线程访问控件。

我收到一条错误信息——有人能给我一些提示吗。

跨线程操作无效:从访问控件"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);
 }

C#跨线程操作无效

您应该调用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);
   }
}