Search code examples
c#system

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


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?


Solution

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