Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to add delay in my code execution

Tags:

c#

winforms

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

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.

like image 230
Leron_says_get_back_Monica Avatar asked Jan 29 '13 17:01

Leron_says_get_back_Monica


2 Answers

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

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
}

And your timer's Elapsed event handler:

private void timer1_TIck(object sender, EventArgs e)
{
    timer1.Enabled = false;
    ResetButtonsDefaultColor();
}
like image 129
Jim Mischel Avatar answered Sep 20 '22 15:09

Jim Mischel


You can always use TPL, its the simplest solution, because you don't need to handle thread contexts or fragment your code.

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);
}
like image 26
DVD Avatar answered Sep 17 '22 15:09

DVD