简体   繁体   中英

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 if s.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM