-4

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

I get an error message - can anyone give me some pointers.

Cross-thread operation not valid: Control 'pbx_1' accessed from a thread other than the thread it was created on.

I have had a look on here but i cant seem to get it to work. I am quite new to c# so I am probably missing something.

 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);
 }
Community
  • 1
  • 1
Gopher2011
  • 169
  • 1
  • 6
  • 16

1 Answers1

0

You should Invoke backgroundWorker1.ReportProgress(1);, because only UI thread can directly access UI controls. Example of invoking:

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);
   }
}
archil
  • 39,013
  • 7
  • 65
  • 82
  • 3
    Milk the points or link duplicates... I see which way you went here [Link 1](http://stackoverflow.com/questions/1353857/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t); [Link 2](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t); [Link 3](http://stackoverflow.com/questions/244591/why-am-i-getting-this-errorcross-thread-operation-not-valid-control-lbfolders); [Link4](http://stackoverflow.com/questions/2237722/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t) – Smudge202 Jul 11 '11 at 11:35
  • Link 1 worked - thanks sport - Not to sure what Milk the points means, but sorry for any confusion. To the other guys - sorry - thread flagged for deletion - apologies. if (pbx_1.Location.X < Click_X) { if (pbx_1.InvokeRequired) { pbx_1.Invoke(new MethodInvoker(delegate { pbx_1.Location = new Point(pbx_1.Location.X + MoveAmt, 20); })); } – Gopher2011 Jul 11 '11 at 13:08