如何在c#中为命令创建延迟?

时间:2016-03-06 04:27:41

标签: c# time timer delay period

我想在我的游戏App中插入延迟更改按钮的颜色2000毫秒...我应该使用什么命令? (我想改变按钮的颜色2秒然后回到正常状态)谢谢

        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;
        }

2 个答案:

答案 0 :(得分:2)

以下是使用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;
    }
}

注意:此代码使用.Net 4.5及更高版本。

答案 1 :(得分:0)

使用Timer管理换色过程,如果您不经常更改,请在每次更改后进行处理。由于您没有提到要更改颜色的位置,因此我将代码放在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;
}