C#에서 Thread.Sleep 메서드는 스레드를 지정된 시간 동안 일시 중지(대기)시키는 데 사용됩니다. 멀티스레딩 환경에서 작업 간의 타이밍을 조절하거나 특정 프로세스가 완료되기를 기다려야 할 때 유용하게 활용할 수 있습니다.
Thread.Sleep 기본 사용법
스레드를 몇 초간 대기시키고 싶다면 밀리초 단위의 값을 인자로 전달하면 됩니다. 예를 들어 2초간 스레드를 중지하려면 다음과 같이 코드를 작성합니다.
int sleepfor = 2000; // 2000밀리초 = 2초 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
코드 설명
Main 메서드에서는 ThreadStart 델리게이트를 통해 자식 스레드를 생성하고 Start() 메서드로 실행합니다. 그러면 CallToChildThread 메서드가 별도의 스레드에서 실행되며, "Child thread starts" 메시지를 출력한 뒤 Thread.Sleep(2000)에 의해 정확히 2초간 일시 중지됩니다. 대기 시간이 끝나면 "Child thread resumes" 메시지와 함께 스레드가 다시 실행을 재개합니다.
이처럼 Thread.Sleep은 스레드의 흐름을 제어하는 가장 기본적이면서도 실용적인 방법으로, 간단한 지연 처리부터 주기적인 작업 수행까지 다양한 상황에서 활용됩니다.