3

I'm learning threads in C# so my first program will be 2 images that will be moving. But the problem is that I get an error when I try to do a new point in a thread:

Here's my code:

namespace TADP___11___EjercicioHilosDatos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int x = 0;
        int y = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread Proceso1 = new Thread(new ThreadStart(Hilo1));
            Proceso1.Start();
        }

        public void Hilo1()
        {   
            while (true) 
            {
                x = pictureBox1.Location.X - 1;
                y = pictureBox1.Location.Y;
                pictureBox1.Location = new Point(x, y);
            }   
        }
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
NathanWay
  • 139
  • 1
  • 8

2 Answers2

6

You can only update a control from the thread that control was created on. Controls do have an Invoke method that you can call from another thread. This method takes a delegate that specifies the work you would like to do on the control's thread:

var updateAction = new Action(() => { pictureBox1.Location = new Point(x,y); });
pictureBox1.Invoke(updateAction);
Tim Destan
  • 2,028
  • 12
  • 16
4

You have to Invoke it. For [obvious] reasons, you can't access controls created by a different thread so you have to use a delegate. Several similar SO questions:

  1. How to update the GUI from another thread in C#? (111 upvotes)
  2. Writing to a textBox using two threads
  3. How to update textbox on GUI from another thread in C#
  4. Writing to a TextBox from another thread?

If you check out the first link, Ian's great answer will demonstrate how you should do this in .Net 2.0 and 3.0. Or you can scroll down to the next answer, Marc's, which will show you how to do it in the simplest way.

Code:

//worker thread
Point newPoint = new Point(someX, someY);
this.Invoke((MethodInvoker)delegate {
pictureBox1.Location = newPoint;
// runs on UI thread
});
Community
  • 1
  • 1
Austin Henley
  • 4,625
  • 13
  • 45
  • 80