James
James

Reputation: 190

Why does Thread.Sleep() method sleep more than expected?

So, my program is basically creating a child thread of Main and get an integer as an input from the user, and convert that number to milisecond by timing it by 1000.

But in the for loop, Thread.Sleep() sleeps about 10 seconds, when I typed number 5 as an input.

The code:

static void CallToChildThread()
{

     Console.WriteLine("How many seconds do you want this thread to rest?");
     int time = Convert.ToInt32(Console.Read());
     int mili = time * 1000;

     for (int i = 0; i < time; i++)
     {
         Console.Write(". ");
         Thread.Sleep(mili);
     }

     Console.WriteLine();

}

So, when I typed 5, and the code will multiply 5 by 1000 and 5000 will be stored in mili.

But, in the for loop, when the Thread.Sleep(mili) is executed, it doesn't sleep whole 5 seconds, it sleeps 10 seconds, when it iterates once through the loop.

Also, when I change substitute mili with 5000 to make the thread sleep for 5 seconds, each time it loops, and it worked, but the loop iterated more than I expected. For example, this is the input I typed:

How many seconds do you want this thread to rest?
5

. . . . . . . . . .      

It counts 5 seconds properly each time it iterates. But it iterated more than 5. If I typed 5 then shouldn't the for loop iterate 5 times and abort? Showing only 5 periods?

Upvotes: 0

Views: 227

Answers (2)

AlexD
AlexD

Reputation: 32596

Console.Read() reads a character, and then you convert it's ASCII code to int.

This prints 53 if you enter 5:

Console.WriteLine("{0}", Console.Read());

BTW, you multiply 5 by 1000, and then sleep for already multiplied value. So the overall time of sleeping in the loop seems to be 5 * 5 * 1000, not 5 * 1000 ms. Is it intentional?

Upvotes: 6

David
David

Reputation: 325

You need to use Console.ReadLine() instead of Console.Read():

int time = Convert.ToInt32(Console.ReadLine());

Upvotes: 3

Related Questions