Thread.Sleep () in C #

I want to make an image viewer in C # Visual Studio 2010 that displays images one by one in seconds:

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

When the program starts, it stops and shows me the first and last image.

+4
source share
4 answers

Thread.Sleep blocks the use of the System.Windows.Forms.Timer UI thread.

+13
source

Use a timer.

First declare your timer and check it every second, calling TimerEventProcessor when it is ticking.

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

Your class will need an image1 array and an int imageCounter variable to keep track of the current image available to the TimerEventProcessor function.

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

Then write what you want to do on each tick

 private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { if (image1 == null || imageCounter >= image1.Length) return; pictureBox1.Image = Image.FromFile(image1[imageCounter++]); } 

Something like this should work.

+10
source

Yes, since Thread.Sleep blocks the user interface thread for 2 seconds.

Use a timer instead.

0
source

If you want to avoid using Timer and defining an event handler, you can do this:

 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(); } 
-1
source

All Articles