Search code examples
c#loopsfor-loopcolorsthread-sleep

Fading color in a loop with C#


I'm trying to make the color of a textbox change to green, and then fade back to white as a method of confirmation. Here's the code I have so far:

private void btnCommit_Click(object sender, EventArgs e)
{
    //do stuff

    Color c = new Color();
    for (int i = 0; i <= 255; i++)
    {
        c = Color.FromArgb(i, 255, i);
        textBox1.BackColor = c;

        System.Threading.Thread.Sleep(10);
    }     
}

It doesn't work. It appears to just wait for the 2.5ish seconds before I can do anything else, but the color stays white the whole time.


Solution

  • Thread.Sleep blocks your UI Thread (If executed using the UI Thread like your case), you have to use Task.Delay() and make your method async to make the UI responsive and see the fading animation:

    private async void btnCommit_Click(object sender, EventArgs e)
    {
        //do stuff
    
        Color c = new Color();
        for (int i = 0; i <= 255; i++)
        {
            c = Color.FromArgb(i, 255, i);
            textBox1.BackColor = c;
    
            await Task.Delay(10);
        }     
    }
    

    Note that the time taken to capture the current context, execute the delay and then resume the context might take the same time (around 20ms) for small delays (1ms vs 20ms). So you might need to increase the delay a little bit to notice a difference between different delays.