I am stuck in my while loop with elapsed time of a timer as condition

Viewed 227

I am starting a timer and I want the method to wait until some time passed. I have searched in other similar questions but cannot find a clear answer. Why is does the following code freeze the app? elapsed time starts at 0 and intervall is 1000 (1sec)

private void timer2_Tick(object sender, EventArgs e)
    {
        elapsedtime2++;
    }

//this is inside my method
timer2.Start();
while (elapsedtime2 < 3)
    {

    }
timer2.Stop();
2 Answers

The easiest way to pause execution for a second is:

Thread.Sleep(1000);

If you're familiar with async/await, the async equivalent is:

await Task.Delay(1000);

You can use events to get the desired behaviour:

private int elapsedtime2 = 0;
private ManualResetEventSlim mre = new ManualResetEventSlim();

private void timer2_Tick(object sender, EventArgs e)
    {
        elapsedtime2++;
        if(elapsedtime2 >= 3)
        {
            mre.Set();
        }
    }

If your elapsed time variable has the expected value, you can set the event.

mre.Reset();
timer2.Start();
mre.Wait();
timer2.Stop();

Before you start the timer, you unset the event. After you started your timer, you wait until the event is set.

Related