Asynchronous alternative to Thread.Sleep without locking application in C#

Asked

Viewed 425 times

3

Sometimes we want our application to wait a few moments to proceed with the next instruction, however the Thread.Sleep(0) can cause crashes in your application, mainly using in loops. So here’s a tip on how to wait for a period you want without causing any application crashes.

2 answers

3

Set a boolean variable:

bool await;

Create an object Windows Timer by name(example) awaitTimer, and in your Tick Event add the following code:

private void awaitTimer_Tick(object sender, EventArgs e)
{
    awaitTimer.Stop();
    await = false;
}

Create a method, here we call Await:

public void Await(int interval)
{
    await = true;
    awaitTimer.Interval = interval;
    awaitTimer.Start();
    while (await)
    {
        Application.DoEvents();
    }
}

To use, simply type Await(*), between parentheses put the time you want to wait for the next instruction in milliseconds.

//Events

Await(1000); //1000 para esperar 1 segundo

//Events

2

You can get the same result without using the timer:

public void Await(int milliseconds)
{
    DateTime dateTimeTarget = DateTime.Now.AddMilliseconds(milliseconds);

    while (DateTime.Now < dateTimeTarget)
    {
        Application.DoEvents();
    }
}

See also the method Task Delay.() from . Net Framework 4.5

  • excellent Vik, thank you very much! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.