How to make the application wait for a while?

12

It is common to have situations that we need to delay the execution of the code for a period, either to show or delete a message or something visual soon after, either to try something again, wait for something in a test or something creative that solves a problem or cause a new one.

The common thing to use is:

Thread.Sleep(3000)

Is this correct?

    
asked by anonymous 09.09.2015 / 16:55

1 answer

11

In fact this is the usual way and is correct if you want to catch the current thread (which is often the main one and therefore hangs the entire application).

But in general it is not what you really want. Usually only useful in testing and debugging. Locking is different from locking although the final effect looks the same in many cases.

And even if it's what you want, it has problems. This creates a thread that is somewhat heavy. It consumes enough memory and spends a lot of processing for its creation and management (context switch).

You must be thinking, "So what do you spend processing?" It takes capacity that could be being used by other applications on a computer. On mobile device is also consuming battery. Do you really want this or use it without thinking about the consequences?

As most of the time you just want to delay the execution of a code and the crash of the application is an unnecessary or even undesirable effect, you have to do it another way.

Before .Net 4.5 would have to build a more complex code to handle this, perhaps using WaitHandles ". But in this version it is possible to use asynchronicity to help.

await Task.Delay(3000);

With the method Task.Delay() you get the delay much more lightly and with await this is done without crashing the application.

It is even possible to create a cancellation token and stop the delay, something that may be desirable in some cases.

See examples in dotNetFiddle and in Coding Ground >.

In this question in SO has some solutions for those who use the older version of .Net. Article showing how TaskDelay() works and how to play it .

Further information is that these delays occur through a timer and its accuracy is low. It depends on the operating system. In current Windows, at least for desktop, it revolves around 15ms. So not only is it useless to use smaller numbers than this one but also you can not have anything out of multiples of it.

    
09.09.2015 / 16:55