C# 程式來實現執行緒的睡眠方法


執行緒的睡眠方法用於在特定時間段內暫停執行緒。

如果你想讓執行緒休眠數秒,則像以下程式碼片段一樣使用它 −

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

示例

你可以嘗試執行以下程式碼來實現執行緒的睡眠方法。

線上演示

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

更新時間: 19-6 月 - 2020

298 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.