Changing image in picture box rapidly

浪子不回头ぞ 提交于 2019-12-13 06:06:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!