The correct way to add delay to my code execution

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) to hide them, and the player must click on the colored squares. So I need a 2 second delay between drawing the squares / buttons and returning the original colors. All code is implemented in the event button_click.

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

This is all the code, but I need to have some delay between calls SetButtonColor()and ReturnButtonsDefaultColor(). All my experiments with Thread.Sleep()so far have not been successful. I get a delay at some point, but the colored squares / buttons are never displayed.

+5
source share
4 answers

, , Sleep .

, - . 2 , . . :

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
}

:

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

TPL, , .

private async void button10_Click(object sender, EventArgs e)
{

    int[,] tempMatrix = new int[3, 3];
    tempMatrix = MakeMatrix();
    tempMatrix = SetDifferentValues(tempMatrix);
    SetButtonColor(tempMatrix, 8);
    if (true)
    {
       await Task.Delay(2000);
       // ReturnButtonsDefaultColor();
    }
    ReturnButtonsDefaultColor();
       await Task.Delay(2000);

    tempMatrix = ResetTempMatrix(tempMatrix);
}
+3

Timer. Thread.Sleep Start() tickback ReturnButtonsDefaultColor(). Thread.Sleep - tick.

+2

:

        private void button10_Click(object sender, EventArgs e)
        {

            int[,] tempMatrix = new int[3, 3];
            tempMatrix = MakeMatrix();
            tempMatrix = SetDifferentValues(tempMatrix);
            SetButtonColor(tempMatrix, 8);

            Task.Factory.StartNew(
                () => 
                {
                    if (true)
                    {
                        Thread.Sleep(1000);
                        // ReturnButtonsDefaultColor();
                    }
                    ReturnButtonsDefaultColor(); //Need to dispatch that to the UI thread
                    Thread.Sleep(2000);

                    tempMatrix = ResetTempMatrix(tempMatrix); //Probably that as well
                });
        }

WPF Winforms, google;)

0
source

All Articles