Search code examples
c#waitsleep

Alternative for Thread.Sleep() to temporarily suspend program


See the code at the bottom of this post. It's supposed to add "3" to the listbox, then "2" a second later, then "1" a second later and then run the main code of the program. However, once I execute the program it just stays blank 3 seconds long, after which all 3, 2, and 1 are shown, after which all the code directly starts. I want to visually see every number show up with a one second delay. How do I do this?

private void Main()
        {
            countdown();
            //Main Code
        }

private void countdown()
        {
            listBox1.Items.Clear();
            listBox1.Items.Add("3");
            System.Threading.Thread.Sleep(1000);
            listBox1.Items.Add("2");
            System.Threading.Thread.Sleep(1000);
            listBox1.Items.Add("1");
            System.Threading.Thread.Sleep(1000);
            listBox1.Items.Clear();
        }

Solution

  • async / await to the rescue:

    private async void OnButtonClick(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        listBox1.Items.Add("3");
        await Task.Delay(1000);
    
        listBox1.Items.Add("2");
        await Task.Delay(1000);
    
        listBox1.Items.Add("1");
        await Task.Delay(1000);
    
        listBox1.Items.Clear();
    }