[英]Why does Thread.Sleep() method sleep more than expected?
因此,我的程序基本上是創建Main的子線程,並從用戶那里獲取一個整數作為輸入,然后通過將其計時1000來將該數字轉換為毫秒。
但是在for循環中,當我輸入數字5作為輸入時,Thread.Sleep()會休眠約10秒。
編碼:
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();
}
因此,當我鍵入5時,代碼會將5乘以1000,而5000將存儲在mili中。
但是,在for循環中,當執行Thread.Sleep(mili)時,它不會在整個5秒鍾內休眠,而在整個循環中迭代一次則休眠10秒鍾。
另外,當我用5000替換替代mili以使線程休眠5秒鍾時,每次它循環時,它都起作用,但是循環的迭代次數超出了我的預期。 例如,這是我輸入的輸入:
How many seconds do you want this thread to rest?
5
. . . . . . . . . .
每次迭代正確計數5秒。 但是它迭代了5次以上。如果我鍵入5,那么for循環是否應該迭代5次並中止? 僅顯示5個期間?
Console.Read()
讀取一個字符,然后將其ASCII代碼轉換為int
。
如果輸入5
則打印53
:
Console.WriteLine("{0}", Console.Read());
順便說一句,將5乘以1000,然后休眠已乘以的值。 因此,在循環中休眠的總時間似乎是5 * 5 * 1000
,而不是5 * 1000
ms。 這是故意的嗎?
您需要使用Console.ReadLine()而不是Console.Read() :
int time = Convert.ToInt32(Console.ReadLine());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.