Code/C#

Thread Abort 사용법과 예제

Hide Code 2007. 12. 8. 16:35
Thread를 중지시키기 위해서 Abort method를 사용할 수 있다.

Abort method 로 thread 를 중지시키면 ThreadAbortException 이 발생한다.

아래 예제는 ThreadAbortException 을 발생시키는 예제이다.

thread 가 실행되는 도중 enter 키를 누르면, thread 가 정지되고, ThreadAbortException 이 발생한다.

using System;
using System.Threading;

namespace AbortThreads
{
   class Program
   {
       static void Main(string[] args)
       {
           Thread.CurrentThread.Name = "MAIN";
           PrintMessage("Application Started.");
           
           Thread worker = new Thread(new ThreadStart(DoWork));
           worker.Name = "WORKER";
           worker.Start();
           
           Console.WriteLine("Press Enter to Abort the Thread!");
           Console.ReadLine();
           worker.Abort();
           Console.WriteLine("Thread abort signal sent.");
           Console.ReadLine();
       }

       static void PrintMessage(string msg)
       {
           Console.WriteLine("[{0}] {1}", Thread.CurrentThread.Name, msg);
       }

       static void DoWork()
       {
           try
           {
               while (true)
               {
                   Console.Write("...");
                   Thread.Sleep(100);
               }
           }
           catch (Exception e)
           {
               PrintMessage("Trapped:" + e.ToString());
           }
       }
   }
}


아래는 실행 화면이다.