C#에서 백그라운드 스레드 여부 확인하기
C#에서 특정 스레드가 백그라운드(background) 스레드인지 확인하려면 Thread 클래스의 IsBackground 속성을 사용하면 됩니다. 이 속성은 해당 스레드가 백그라운드 스레드이면 true, 포어그라운드(foreground) 스레드이면 false를 반환합니다.
백그라운드 스레드는 프로세스 종료에 영향을 주지 않으며, 모든 포어그라운드 스레드가 종료되면 자동으로 함께 종료됩니다. 반면 포어그라운드 스레드는 실행이 끝날 때까지 프로세스가 유지됩니다.
예제 1: 현재 스레드가 백그라운드 스레드인지 확인
using System;
using System.Threading;
public class Demo {
public static void Main() {
Thread thread = new Thread(new ThreadStart(demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(demo2));
Console.WriteLine("Current state of Thread = " + thread.ThreadState);
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
Console.WriteLine("Is the Thread a background thread? = " + Thread.CurrentThread.IsBackground);
}
public static void demo1() {
Thread.Sleep(2000);
}
public static void demo2(object stateInfo) {
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
실행 결과
Current state of Thread = Unstarted
ManagedThreadId = 721
Is the Thread a background thread? = False
Thread belongs to managed thread pool? = True
위 예제에서 Thread.CurrentThread.IsBackground는 메인 메서드를 실행 중인 현재 스레드에 대한 정보를 출력합니다. 결과값이 False인 것을 통해 기본적으로 생성된 스레드는 포어그라운드 스레드임을 알 수 있습니다. 또한 IsThreadPoolThread 속성을 통해 해당 스레드가 관리되는 스레드 풀(managed thread pool)에 속한 스레드임을 확인할 수 있습니다.
예제 2: 새로 생성한 스레드를 백그라운드 스레드로 변경
새로 생성한 스레드의 IsBackground 속성 값을 직접 설정하면 해당 스레드를 백그라운드 스레드로 전환할 수 있습니다.
using System;
using System.Threading;
public class Demo {
public static void Main() {
Thread thread = new Thread(new ThreadStart(demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(demo2));
Console.WriteLine("Current state of Thread = " + thread.ThreadState);
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
thread.IsBackground = true;
Console.WriteLine("Is the Thread a background thread? = " + thread.IsBackground);
}
public static void demo1() {
Thread.Sleep(2000);
}
public static void demo2(object stateInfo) {
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
실행 결과
Current state of Thread = Unstarted
ManagedThreadId = 1114
Is the Thread a background thread? = True
Thread belongs to managed thread pool? = True
두 번째 예제에서는 thread.IsBackground = true; 구문으로 스레드를 명시적으로 백그라운드 스레드로 지정했습니다. 그 결과 IsBackground 값이 True로 출력되는 것을 확인할 수 있습니다.
핵심 정리
- IsBackground 속성: 스레드가 백그라운드 스레드인지 여부를 읽거나 설정할 수 있습니다.
- 기본값:
new Thread()로 생성한 스레드는 기본적으로 포어그라운드(false)입니다. - 설정 시점 주의: 스레드가 시작된 이후에는
IsBackground값을 변경할 수 없으므로, 반드시Start()호출 전에 설정해야 합니다. - 스레드 풀 스레드:
ThreadPool의 스레드는 항상 백그라운드 스레드입니다.