如何在 C# 中使用睡眠方法?


執行緒的 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

更新於: 2020 年 6 月 20 日

725 次瀏覽

開啟你的 事業

完成課程獲得認證

開始學習
廣告