如何讓 C# 程式休眠 x 毫秒?


要讓一個 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();

         //stop the main thread for some time
         Thread.Sleep(5000);
      }
   }
}

輸出

In Main: Creating the Child thread
Child thread starts
0
1
2
3
4
5
6
7
8

更新於:2020 年 6 月 22 日

1K+ 次瀏覽

開啟您的職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.