Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

waiting for a second every time in a loop in c# using Thread.Sleep

Tags:

c#

system

i'm trying to print "p" to the screen every second.

when I run this:

while (true)
    Thread.Sleep(1000); 
    Console.WriteLine("p");

it doesn't print at all. But when I run this:

while (true)
    Console.WriteLine("p");
    Thread.Sleep(1000); 

Its printing without waiting at all. Can somebody please explain this to me and suggest a fix?

like image 310
avrum Avatar asked Nov 13 '19 15:11

avrum


2 Answers

You are not looping the whole code

This :

while (true)
    Thread.Sleep(1000); 
    Console.WriteLine("p");

Is the same as this :

while (true)
{
    Thread.Sleep(1000); 
}
Console.WriteLine("p");

You need to explicitly set your braces around all the lines you want the loop to perform otherwise it only loop on the next instruction.

Something like this is what you are looking for :

while (true)
{
    Thread.Sleep(1000); 
    Console.WriteLine("p");
}
like image 104
Franck Avatar answered Oct 26 '22 08:10

Franck


why didn't it work without braces?

C# is not Python. In Python, program structure is indicated by spaces. In C# whitespace is ignored entirely and program structure is determined by the grammar of the language.

In C# a block of the form { any number of statements } is itself a statement.

The grammar of while is

while( an expression that can be evaluated to bool ) 
    a single statement

But since { ... } is a single statement, if you want multiple statements in the body of your while, or if, or for or foreach and so on, you use a block.

Incidentally, you should not be using Thread.Sleep in the first place. It should only be used in testing code. Threads are expensive program resources; do not pay them to sleep! If you want to introduce a delay, then there are two things to do. In an event-driven program, start a timer and then handle the timer event when it goes off. Or, make your program asynchronous and await a Task.Delay. Sleeping is a bad practice and indicates that there is some flaw in your program design.

Now, you might say, hey, this is a console program and I genuinely want to introduce a delay in my user experience, and I don't have any events processing in the background, and so on, so why not Sleep? And I can understand that argument; it is convenient. However, (1) get in good habits now while you are still a beginner and you won't have to break them later, and (2) programs evolve. At some point you're going to want to write a program that stays interactive and responds to user keypresses, or network traffic, or some other such thing, while the UI is paused; if your threads are asleep, they're not responding to those events.

like image 25
Eric Lippert Avatar answered Oct 26 '22 07:10

Eric Lippert