Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# 스레딩 핵심 메서드: Join, Sleep, Abort 완벽 가이드

Join

Join() 메서드는 호출한 스레드를 차단(block)하여 대상 스레드가 종료될 때까지 대기하도록 합니다. 대기 중에도 표준 COM 및 SendMessage 펌핑은 계속 수행되므로 메시지 처리에는 지장이 없습니다. 또한 이 메서드는 밀리초 단위의 시간 제한을 지정할 수 있는 등 여러 가지 오버로드 형태를 제공합니다.

Sleep

Sleep() 메서드는 현재 스레드를 지정된 시간(밀리초) 동안 일시 중지시킵니다. 스레드의 실행 흐름을 잠시 멈추거나 작업 사이에 간격을 두고 싶을 때 유용하게 사용됩니다.

Abort

Abort() 메서드는 실행 중인 스레드를 강제로 종료(파괴)하는 데 사용됩니다. 호출 시 해당 스레드 내부에서 ThreadAbortException이 발생하며, finally 블록은 반드시 실행됩니다.

참고: Thread.Abort는 .NET Framework에서만 지원되며, .NET Core 및 .NET 5 이상에서는 PlatformNotSupportedException이 발생합니다. 최신 .NET 환경에서는 CancellationToken이나 플래그 변수를 활용해 스레드를 안전하게 종료하는 방식이 권장됩니다.

예제 1: Join() 사용하기

using System;
using System.Diagnostics;
using System.Threading;

namespace Sample {
   class Demo {
      static void Run() {
         for (int i = 0; i < 2; i++)
            Console.Write("Sample text!");
      }

      static void Main(string[] args) {
         Thread t = new Thread(Run);
         t.Start();
         t.Join(); // 자식 스레드가 끝날 때까지 대기
         Console.WriteLine("Thread terminated!");
         Console.Read();
      }
   }
}

위 코드에서 t.Join()을 호출하면 메인 스레드는 자식 스레드 t가 모든 작업을 마칠 때까지 기다린 뒤에야 다음 문장을 실행합니다.

예제 2: Sleep()과 Abort() 사용하기

using System;
using System.Threading;

namespace Demo {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         try {
            Console.WriteLine("Child thread starts");
            // 10까지 카운트하는 작업 수행
            for (int counter = 0; counter <= 10; counter++) {
               Thread.Sleep(500);
               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");
         }
      }

      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();

         // 메인 스레드를 잠시 멈춤
         Thread.Sleep(2000);

         // 자식 스레드 강제 종료
         Console.WriteLine("In Main: Aborting the Child thread");
         childThread.Abort();
         Console.ReadKey();
      }
   }
}

이 예제에서는 자식 스레드가 0부터 10까지 0.5초 간격으로 숫자를 출력하는 동안, 메인 스레드는 2초 후 childThread.Abort()를 호출해 자식 스레드를 강제 종료합니다. 이때 자식 스레드에서는 ThreadAbortException이 발생하고, catch 블록과 finally 블록이 순서대로 실행되는 것을 확인할 수 있습니다.