Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách dùng phương thức Sleep trong C#

Phương thức Thread.Sleep của luồng (thread) dùng để tạm dừng luồng hiện tại trong một khoảng thời gian xác định (milliseconds).

Cú pháp:

int sleepFor = 2000; // 2000 ms = 2 giây
Thread.Sleep(sleepFor);

Ví dụ: Tạo child thread và 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();
        }
    }
}

Kết quả

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

Lưu ý:

  • Thread.Sleep(0): Nhường CPU cho thread khác cùng priority.
  • Thread.Sleep(Timeout.Infinite): Ngủ vô hạn cho đến khi Thread.Interrupt().
  • Hiện đại: Dùng Task.Delay(ms) với await cho async/await non-blocking.