Search code examples
c#asynchronoustimer

Delay function in C#


I need to understand how can I create delays between a set of commands. My background is with C (DOS) and now reviving the concepts using C# in Visual Studio 2015. This is the code I am struggling with:

using System.Threading;

private void button1_Click(object sender, EventArgs e)      // Button
{
    int i;
    for (i = 0; i < 10; i++)
    {
        textBox1.BackColor = Color.Red;
        Thread.Sleep(100);
        textBox1.BackColor = Color.Yellow;
        Thread.Sleep(100);
    }
}

I was expecting the background color of the textbox will change alternatively 10 times but I could see only yellow color after the loop finishes. If I increase delay I do notice that program takes time to finish. I went through some related articles but couldn't get the point. Any help will be appreciated. Thanks


Solution

  • Use an async method to create a delay using the built-in Task.Delay method. This will cause execution to be paused and then resumed after the specified time without blocking the current thread.

    async Task UseDelay()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
    }
    

    In your specific case

    /// <remarks>
    /// `async void` is only acceptable because
    /// this has to conform to events.
    /// Otherwise, we'd use `async Task`.
    /// </remarks>
    async void button1_Click(object sender, EventArgs e)
    {
        for (var i = 0; i < 10; i++) 
        {
            textBox1.BackColor = Color.Red;         
            await Task.Delay(TimeSpan.FromMilliseconds(100);
            textBox1.BackColor = Color.Yellow;    
            await Task.Delay(TimeSpan.FromMilliseconds(100));
        }
     }