正确的方法在我的代码执行增加延迟 [英] Proper way to add delay in my code execution

查看:156
本文介绍了正确的方法在我的代码执行增加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个很简单的逻辑游戏。我们的想法是,看一个矩阵具有一定数目的彩色方块(按钮),然后将其隐藏和玩家有点击着色方块。所以我需要2秒延迟绘画之间的平方/按钮并返回原来的颜色。所有的代码是在 button_click 事件来实现。

I am trying to make a very simple logic game. The idea is to see a matrix with a certain number of colored squares(buttons) then to hide them and the player has to click the colored squares. So I need a 2 second delay between the painting the squares/buttons and returning the original colors. All the code is implemented in a button_click event.

private void button10_Click(object sender, EventArgs e)
{

    int[,] tempMatrix = new int[3, 3];
    tempMatrix = MakeMatrix();
    tempMatrix = SetDifferentValues(tempMatrix);
    SetButtonColor(tempMatrix, 8);
    if (true)
    {
        Thread.Sleep(1000);
       // ReturnButtonsDefaultColor();
    }
    ReturnButtonsDefaultColor();
    Thread.Sleep(2000);

    tempMatrix = ResetTempMatrix(tempMatrix);
}

这是整个代码,但我需要的是有之间的一些延迟调用 SetButtonColor() ReturnButtonsDefaultColor()。我与的Thread.Sleep所有实验()满足没有成功到现在。我得到在某些时候的延迟,但是颜色的方块/按钮永远不会显示。

This is the whole code, but what I need is to have some delay between calling SetButtonColor() and ReturnButtonsDefaultColor(). All my experiments with Thread.Sleep() meet no success till now. I get a delay at some point, but the colored squares/buttons are never shown.

推荐答案

您看不到按钮改变颜色,因为睡眠呼叫防止被处理的消息。

You don't see the buttons change color because the Sleep call prevents messages from being processed.

大概来处理最简单的方法是用计时器。初始化延迟2秒计时器,并确保它在默认情况下禁用。然后,你按一下按钮代码使计时器。像这样的:

Probably the easiest way to handle this is with a timer. Initialize the timer with a 2 second delay and make sure that it's disabled by default. Then, your button click code enables the timer. Like this:

private void button10_Click(object sender, EventArgs e)
{
    // do stuff here
    SetButtonColor(...);
    timer1.Enabled = true; // enables the timer. The Elapsed event will occur in 2 seconds
}

和您的计时器的Elapsed事件处理程序:

And your timer's Elapsed event handler:

private void timer1_TIck(object sender, EventArgs e)
{
    timer1.Enabled = false;
    ResetButtonsDefaultColor();
}

这篇关于正确的方法在我的代码执行增加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆