快速更改图片框中的图像

时间:2013-10-21 08:51:19

标签: c# picturebox

我试图快速连续显示3张图像,每张图像约200毫秒。这是我现在的代码:

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

我对这段代码的问题是图片没有显示在我的图片框中,只有暂停就是这样。如果有人可以帮助我,我将不胜感激!

2 个答案:

答案 0 :(得分:3)

我建议您标记方法async并使用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
        }
    }
}

答案 1 :(得分:0)

您的代码使UI线程保持忙碌,因此会阻止UI(包括更新其图形状态)。避免使用Thread.Sleep(200);;改为使用计时器或async / await。这样,在等待200ms传递时,UI线程不会被阻塞。

相关问题