C#中的Thread.Sleep()

我想在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); } 

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

Thread.Sleep阻止你的UI线程使用System.Windows.Forms.Timer 。

使用计时器。

首先声明你的Timer并将其设置为每秒滴答一次,当它滴答时调用TimerEventProcessor

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

您的类将需要image1数组和一个int变量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++]); } 

这样的事情应该有效。

是的,因为Thread.Sleep在2s期间阻止了UI线程。

请改用计时器。

如果要避免使用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(); }