I have a problem with Multithreading.
I'm doing a project in which we have a train, rail crossing and a car. The train is moving, and the rail crossing and car stop if required. All three thing are on different threads. there are 2 buttons, one starts moving the train, the second creats a new PictureBox car.
To move train I used simply use for
loop that by Invoke
changes the location of the PictureBox.
The rail crossing just checks the location of the train and changes the light to red when the train is in a specific location.
Creating the car looks like this :
private void Operation1()
{
this.BeginInvoke((MethodInvoker)delegate()
{
PictureBox a = new PictureBox();
a.Location = new Point(333, 361);
a.BackColor = Color.Black;
a.Size = new Size(20, 37);
Controls.Add(a);
});
}
The car is created and it's fine.
Now I would like to move a car in Operation1()
with loop like this:
private void Operation1()
{
this.BeginInvoke((MethodInvoker)delegate()
{
PictureBox a = new PictureBox();
a.Location = new Point(333, 361);
a.BackColor = Color.Black;
a.Size = new Size(20, 37);
Controls.Add(a);
for (int i = 0; i < 140; i++)
{
a.Location = new Point(a.Location.X, a.Location.Y - 3);
Thread.Sleep(50);
}
});
}
But when it starts the car disappears, if the other thread was running it stops and waits until this loop ends. Where is the problem? I hope someone can help me as fast as possible.