如何让 C# 程序休眠 x 毫秒?
csharpprogrammingserver side programming更新于 2025/5/24 17:52:17
要让 C# 程序休眠 x 毫秒,请使用 Thread.Sleep() 方法。
将其设置为 1000 毫秒 -
Thread.Sleep(1000);
以下代码展示了如何为线程设置计数器,并将其设置为在每次 for 循环迭代时休眠 1000 毫秒 −
示例
using System;
using System.Threading;
namespace MultithreadingApplication {
public class ThreadCreationProgram {
public static void CallToChildThread() {
try {
Console.WriteLine("Child thread starts");
for (int counter = 0; counter <= 10; counter++) {
Thread.Sleep(1000);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
} catch (ThreadAbortException e) {
Console.WriteLine("Thread Abort Exception");
} finally {
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
public static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
//暂停主线程一段时间
Thread.Sleep(5000);
}
}
}
输出
In Main: Creating the Child thread Child thread starts 0 1 2 3 4 5 6 7 8

