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

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

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.

Tags:

C#

System