Berindean Ionut
Berindean Ionut

Reputation: 3

Thread.Sleep not working properly

So I have a picturebox which should switch certain photos after an amount of time.

for(int i=1;i<=7;i++)
{
    if (i == 1) { pictureBox1.Image = Properties.Resources.unu; Console.Beep();   }
    if (i == 2) { pictureBox1.Image = Properties.Resources.doi; Console.Beep();   }
    if (i == 3) { pictureBox1.Image = Properties.Resources.trei; Console.Beep();  }
    if (i == 4) { pictureBox1.Image = Properties.Resources.patru; Console.Beep(); }
    if (i == 5) { pictureBox1.Image = Properties.Resources.cinci; Console.Beep(); }
    if (i == 6) { pictureBox1.Image = Properties.Resources.sase; Console.Beep();  }
    Thread.Sleep(100);
}

Note: I've inserted the Console.Beep just to see if the program enters the ifs.

I hear the beeps but the image doesn`t change, it remains the default. Why?

Upvotes: 0

Views: 354

Answers (2)

David
David

Reputation: 10708

By using a blocking call like this, your program can't reenter the UI code and update the image until after it's finished - which means it won't seem to change. Furthermore, depending on what you're using for UI (you should probably tag you question with this!) you may need to call picturebox1.Update() or .Refresh() in order to force the control to redraw.

Also note that since operations can be very very fast depending on what you're doing, you'll want to insert Thread.Sleep(...) calls or some way to wait for user input between each image change, or you'll see a blur of images at best, and only the last image appear at worst. If you're using a framework which requires you to call .Update(), you'll need to do that between image swaps as well.

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151720

Because your application doesn't handle events until you're out of the loop. Use a Timer.

Upvotes: 3

Related Questions