C# 程序实现线程的 Sleep 方法

csharpserver side programmingprogramming更新于 2025/9/24 2:49:00

线程的 sleep 方法用于暂停线程特定时间。

如果要设置睡眠几秒钟,请像以下代码片段一样使用它 −

int sleepfor = 2000;
Thread.Sleep(sleepfor);

示例

您可以尝试运行以下代码来实现线程的 sleep 方法。

using System;
using System.Threading;
namespace MyApplication {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         Console.WriteLine("Child thread starts");
         int sleepfor = 2000;
         Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
         Thread.Sleep(sleepfor);
         Console.WriteLine("Child thread resumes");
      }
      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();
         Console.ReadKey();
      }
   }
}

输出

In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 2 seconds
Child thread resumes

相关文章