How to pause execution for few seconds and continue the loop?

mrN picture mrN · Aug 10, 2011 · Viewed 15.9k times · Source

I am creating a small applicaiton for simulating dice roll. To simulate bounces I change the position of the picture randomly. Now to simulate more than one bounce, I used a for loop to continuously change the position of the picture box. But it is not happening as I planned, the form only displays the position of the last loop. I even tried using System.Threading.Thread.Sleep(1000) hoping to show the bounces, but even they show the last loop only.

For bounceCount As Integer = 1 To bounces
    bounce(pb_dice1)
    bounce(pb_dice2)
    System.Threading.Thread.Sleep(3000) 'I need to pause here and show the recent change in position then continue after 3 seconds
Next

the bounce method changes the position of the PictureBox.

How can I pause my for loop, display the newly positioned dices, and then continue after 3 seconds?

Answer

Hand-E-Food picture Hand-E-Food · Aug 10, 2011

Controls don't refresh their graphics until event handlers finish executing. Otherwise, if several changes were made to one or more controls, they would refresh repeatedly when all you really want is the end result.

To force a control to refresh it's graphics, you need to insert the following line before sleeping:

PictureBox1.Refresh()

You may have to change PictureBox1 to the name of another control, of course. Also, it may be worth refreshing the parent control (ie. the control that contains the dice.)