Reputation: 13
I am trying to get these two pictureboxes to increase in size then decrease in size at the same time using two different methods / while loops. How can I do this? The it works is that when the button is clicked the two picture boxes will increase in size till it reaches a given size then they will both decrease in size.
private void bthGraph_Click(object sender, EventArgs e)
{
red();
blue();
}
private void btnReset_Click(object sender, EventArgs e)
{
pbxBlue.Width = 10;
pbxRed.Width = 10;
}
public void red()
{
int width = 10;
while (width < 156)
{
width++;
pbxRed.Width = width;
pbxRed.Refresh();
Thread.Sleep(10);
}
while (width > 10)
{
width--;
pbxRed.Width = width;
pbxRed.Refresh();
Thread.Sleep(10);
}
}
private void blue()
{
while (pbxBlue.Width < 156)
{
pbxBlue.Width++;
pbxBlue.Refresh();
Thread.Sleep(10);
}
while (pbxBlue.Width > 10)
{
pbxBlue.Width--;
pbxBlue.Refresh();
Thread.Sleep(10);
}
}
}
Upvotes: 1
Views: 131
Reputation: 8940
Every Control can only be updated by the Thread that created it, that said you just cannot access the UI from two threads* simultaneously therefore you just can't achieve what you are trying to do in this way. If you wan't to create an animation why do you need two methods ?
And you should (as already mentioned in the Comments) get rid of the "Thread.Sleep" in the UI Thread, better use a Timer.
*There is a very dirty way to do this by setting the Property CheckForIllegalCrossThreadCalls to false. But this should NEVER be done as it leads to unexpected and untraceable bugs.
Upvotes: 0
Reputation: 1072
try this way
private void bthGraph_Click(object sender, EventArgs e)
{
Task[] tasks = new Task[]
{
new Task(red),
new Task(blue),
};
foreach(var task in tasks)
task.Start();
new Task(red).Start();
new Task(blue).Start();
}
Upvotes: 2