Ali.Ghzd
Ali.Ghzd

Reputation: 319

How to create a delay for a command in c#?

I want to insert delay for changing color of button for 2000 milisecond in my game App in c# ... what command should I use for it ?? ( I want to changes color of button for 2 sec and then come back to normal state ) thank you

        switch (colorNum)
        {
            case 1:
                btnRed.BackColor = Color.Red

                btnRed.BackColor = Color.LightCoral;
                firedColors[count] = "Red";
                count++;
                break;
            case 2:
                btnBlue.BackColor = Color.Blue;

                btnRed.BackColor = Color.LightBlue;
                firedColors[count] = "Blue";
                count++;
                break;
            case 3:
                btnYellow.BackColor = Color.Gold;

                btnYellow.BackColor = Color.LightYellow;
                firedColors[count] = "Yellow";
                count++;
                break;
        }

Upvotes: 3

Views: 348

Answers (2)

Ghasem
Ghasem

Reputation: 15643

Use a Timer to manage the color changing process and dispose it after each changing if you're not going to change it frequently. Since you didn't mentioned where are you going to change the color, I placed the code in a Button.

private Color _originalColor = Color.LightGray;
private Color _newColor = Color.LightSkyBlue;
private bool _isOrigColor = true;
Timer _tmrChangeColor;

private void btnTest_Click(object sender, EventArgs e)
{
    if (_tmrChangeColor != null) return;
    _tmrChangeColor = new Timer {Interval = 2000, Enabled = true};
    _tmrChangeColor.Tick += _tmrChangeColor_Tick;
}

void _tmrChangeColor_Tick(object sender, EventArgs e)
{
    btnTest.BackColor = _isOrigColor ? _newColor : _originalColor;
    _isOrigColor = !_isOrigColor;
    _tmrChangeColor.Dispose();
    _tmrChangeColor = null;
}

Upvotes: 0

NoName
NoName

Reputation: 8025

Here is one way you can do it with async - await:

using System.Threading.Tasks;

async void YourFunction()   // <--- Use "async" keyword
{
    switch (colorNum)
    {
        case 1:
            btnRed.BackColor = Color.Red;
            await Task.Delay(2000);
            btnRed.BackColor = Color.LightCoral;
            firedColors[count] = "Red";
            count++;
            break;
        case 2:
            btnBlue.BackColor = Color.Blue;
            await Task.Delay(2000);
            btnRed.BackColor = Color.LightBlue;
            firedColors[count] = "Blue";
            count++;
            break;
        case 3:
            btnYellow.BackColor = Color.Gold;
            await Task.Delay(2000);
            btnYellow.BackColor = Color.LightYellow;
            firedColors[count] = "Yellow";
            count++;
            break;
    }
}

Note: this code use .Net version 4.5 and above.

Upvotes: 2

Related Questions