问题
I am trying to display 3 images in rapid succession, around 200ms per image. Here is the code right now i have:
for (int i = 0; i < 3; i++)
{
if ((_currentGridPos >= 0 && _currentGridPos < 2) || (_currentGridPos >= 3 && _currentGridPos < 5))
{
pictureBox1.Image = Image.FromFile(@"C:\Users\Nyago\Images\g" + _currentGridPos + "_r" + i + ".JPG");
pictureBox1.Refresh();
Thread.Sleep(200);
}
}
The problem I am having with this code is that the images aren't showing up in my picture box, there is just the pause then thats it. If someone could help me it would be greatly appreciated!
回答1:
I'll suggest you to mark the method async
and use Task.Delay
private async void DoSomething()
{
for (int i = 0; i < 3; i++)
{
if ((_currentGridPos >= 0 && _currentGridPos < 2) || (_currentGridPos >= 3 && _currentGridPos < 5))
{
pictureBox1.Image = Image.FromFile(@"C:\Users\Nyago\Images\g" + _currentGridPos + "_r" + i + ".JPG");
pictureBox1.Refresh();
await Task.Delay(200);//<--Note Task.Delay don't block UI
}
}
}
回答2:
Your code keeps the UI thread busy and therefore blocks the UI (including updating its graphical state). Avoid using Thread.Sleep(200);
; use a timer or async/await instead. That way, the UI thread is not blocked while waiting for the 200ms to pass.
来源:https://stackoverflow.com/questions/19489955/changing-image-in-picture-box-rapidly