C#中的Thread.Sleep()

6
我希望在C# Visual Studio 2010 中制作一个图像查看器,每秒显示一张图片:
i = 0;

if (image1.Length > 0) //image1 is an array string containing the images directory
{
    while (i < image1.Length)
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(image1[i]);
        i++;
        System.Threading.Thread.Sleep(2000);
    }

当程序启动时,它会停止并仅显示第一张和最后一张图片。

7
你正在阻塞用户界面线程。 - Michal Klouda
你总是覆盖pictureBox1.Image。 - Amiram Korach
我猜它在中间睡觉了 ;) - Thread.Sleep(123)会停止整个线程,这种情况下包括图像显示。如果不知道周围的代码,使用计时器可能会更好些。 - ChriPf
1
不确定为什么你被踩了?在我看来,这是一个好问题。 - CaffGeek
和 @Chad 有同样的感觉,+1 给 OP。 - Jamie Keeling
4个回答

17

1
使用 System.Windows.Forms.Timer 有什么特殊的原因吗? - ChriPf
5
由于Windows Forms计时器Tick事件自动在UI线程上运行,因此无需调用Invoke。 - Chris Shain
解释:当窗口重绘时,它会显示图片。重绘是一个UI线程事件。如果您阻塞该线程,则没有UI更新,也没有其他UI交互,因此也不会有按钮点击等操作。 - TomTom

14

使用计时器。

首先声明一个计时器并将其设置为每秒一次的间隔,当计时器触发时调用TimerEventProcessor函数。

static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1000;
myTimer.Start();

您的类将需要 image1 数组和一个整数变量 imageCounter 来跟踪当前图像,以便 TimerEventProcessor 函数可以访问。

var image1[] = ...;
var imageCounter = 0;

然后编写您希望在每次时钟周期中发生的内容

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {
    if (image1 == null || imageCounter >= image1.Length)
        return;

    pictureBox1.Image = Image.FromFile(image1[imageCounter++]);
}

像这样应该可以工作。


我在 Visual Studio Mac 类中没有看到 System.Windows.Form.Timer。虽然有 System.Threading.Timer 但语法不同。 - 1.21 gigawatts

0
如果你想避免使用Timer和定义事件处理程序,你可以这样做:
DateTime t = DateTime.Now;
while (i < image1.Length) {
    DateTime now = DateTime.Now;
    if ((now - t).TotalSeconds >= 2) {
        pictureBox1.Image = Image.FromFile(image1[i]);
        i++;
        t = now;
    }
    Application.DoEvents();
}

0

是的,因为Thread.Sleep在2秒期间会阻塞UI线程。

改用计时器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接