C#에서 Thread 만들고 종료하기
다른 스레드에서 Abort()를 호출하여 스레드를 종료하는 방법을 사용하면,
스레드의 작업이 완료 여부와 관계없이 스레드가 종료되어 리소스를 정리할 수도 없게 된다.
아래와 같은 방식으로 종료하자. (펌: MSDN)
using System;
using System.Threading;
public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
workerThread.IsBackground = true;
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
// Loop until worker thread activates. !..
// 작업자 스레드가 실행되기도 전에 Main함수가 이 스레드를 종료하지 않도록 하기 위해..!
while (!workerThread.IsAlive) ;
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);
// Request that the worker thread stop itself:
workerObject.RequestStop();
// Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}
출처: https://msdn.microsoft.com/ko-kr/library/7a2f3ay4(v=VS.90).aspx