user2184723
user2184723

Reputation: 5

Changing image in picture box rapidly

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!

Upvotes: 0

Views: 2328

Answers (2)

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

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.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

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
        }
    }
}

Upvotes: 3

Related Questions