Search code examples
c#timerwait

How to have program wait X seconds and allow UI to execute?


I am making a small game with an auto play feature, but the program runs too fast so the user can't see the outcome at each stage. I am using VS 2017, so I can't use async (at least from what I have read). How can I have the program wait and allow the UI to update?

I am working in a do while loop. The main chunk of the game executes, updates the UI, and then waits for the player to click a button (assuming auto play is not running), with auto play running the do while loop repeats, but after the UI updates it would wait X seconds.


Solution

  • It looks like you have a couple of options

    1.You can try Sleep -(but it may hang the UI)

     int Seconds = 1;
     Threading.Thread.Sleep(Seconds * 1000);
    

    2.You can try this code:

    int Seconds = 1;
    Private void WaitNSeconds(int seconds)
        { 
           if (seconds < 1) return;
             DateTime _desired = DateTime.Now.AddSeconds(seconds);
             while (DateTime.Now < _desired) {
                  System.Windows.Forms.Application.DoEvents();
             }
         }
    

    3.Try to use Async and see what happens

    async Task MakeDelay() {
          await Task.Delay(5000); 
    }   
    private async void btnTaskDelay_Click(object sender, EventArgs e) {
          await MakeDelay();          
    }