6

I want to make an image viewer in C# Visual Studio 2010 which displays images one by one after 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 just shows me the first and last image.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alyafey
  • 1,455
  • 3
  • 15
  • 23

4 Answers4

17

Thread.Sleep blocks your UI thread use System.Windows.Forms.Timer instead.

L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    any special reason to use System.Windows.Forms.Timer? – ChriPf Aug 20 '12 at 14:46
  • 5
    @ChriPf because the Windows Forms timer tick events automatically runs on the UI thread. No need to Invoke. – Chris Shain Aug 20 '12 at 14:50
  • TO explain: The windows shows the picture when it redraws. THe redraw is a UI thread event. You block the thread, no UI updates - and no other UI interaction either, so no button clicks etc. – TomTom Apr 13 '14 at 19:10
14

Use a Timer.

First declare your Timer and set it to tick every second, calling TimerEventProcessor when it ticks.

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 the image1 array and an int variable imageCounter to keep track of the current image accessible to the TimerEventProcessor function.

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

Then write what you want to happen 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.

CaffGeek
  • 21,856
  • 17
  • 100
  • 184
  • I do not see System.Windows.Form.Timer on Visual Studio Mac classes. There is System.Threading.Timer but the syntax is different. – 1.21 gigawatts May 15 '21 at 11:16
0

Yes, because Thread.Sleep blocks the UI thread during the 2s.

Use a timer instead.

ken2k
  • 48,145
  • 10
  • 116
  • 176
0

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();
}
d3dave
  • 1,361
  • 14
  • 23