Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Thread 타입의 Suspend/Resume/Join 사용 관련 예외 처리

참고로 Suspend와 Resume 메서드는 몇 년째 obsolete로 표시되어 권장하지 않는 메서드입니다. 그래도 사용해야 한다면 이 글을 한번쯤 읽어보시고 사용하시길 바랍니다. ^^

우선, 다음과 같이 간단하게 예제를 만들어,

static void Main(string[] args)
{
    while (true)
    {
        Thread t = new Thread(threadFunc);
        t.Start(i);
        t.Suspend();
        t.Resume();
        t.Join();
    }
}

private static void threadFunc(object obj)
{
    Console.WriteLine("TEST: " + obj);
}

실행해 보면 다음과 같은 2개의 에러를 (상황에 따라) 만날 수 있습니다.

Unhandled Exception: System.Threading.ThreadStateException: Thread is not running; it cannot be suspended.
   at System.Threading.Thread.SuspendInternal()
   at System.Threading.Thread.Suspend()
   at ConsoleApp1.Program.Main(String[] args) 

Unhandled Exception: System.Threading.ThreadStateException: Thread is not running; it cannot be resumed.
   at System.Threading.Thread.ResumeInternal()
   at System.Threading.Thread.Resume()
   at ConsoleApp1.Program.Main(String[] args)

즉, Thread가 수행중이지 않았을 때 Suspend/Resume 메서드 호출을 하면 모두 예외가 발생하는 것입니다. 근데, 위의 에러 상황이 Suspend는 그렇다 치고 Resume의 경우에 발생하는 것은 이해가 안될 수도 있습니다. Suspend 한 시점에는 적어도 스레드가 실행 중이었으니 예외가 안 났다는 것이고 당연히 Suspend 호출로 인해 실행 중이었던 스레드는 중지했을 것입니다. 그런데 왜 Resume을 했는데 스레드가 실행 중이지 않고 있다면서 예외가 발생하는 것일까요?

그 이유는, Suspend 메서드는 대상 스레드에 중지하라는 신호만 날리는 비동기 식 호출이기 때문입니다. CLR은 대상 스레드가 중지해도 되는 상황이면 바로 중지를 하지만 그렇지 못한 상황이면 SuspendRequested로 접수를 해둡니다. 따라서 t.Suspend 메서드 호출이 완료되었어도 대상 스레드는 그 순간에 중지못했을 수도 있으니 위와 같은 상황에서는 스레드 종료까지 이어졌을 수도 있습니다. 그리곤 Resume을 호출하니 예외가 발생한 것이고.




또 다른 경우도 있습니다. 테스트하다 보면 다음의 라인에서 수행이 정지하는 경우가 있습니다.

static void Main(string[] args)
{
    while (true)
    {
        Thread t = new Thread(threadFunc);
        t.Start(i);
        Console.WriteLine(t.IsAlive);
        t.Suspend();
        Console.WriteLine(t.IsAlive); // 실행 정지
        t.Resume();
        t.Join();
    }
}

private static void threadFunc(object obj)
{
    Console.WriteLine("TEST: " + obj);
}

// 화면 출력 상태
True
TEST: 1

얼핏 보면 t 스레드의 IsAlive 속성을 얻어오지 못하고 blocking 상태에 빠진 듯 한데요. 실제 이유는 콜스택을 보면 알 수 있습니다.

// Hang 상태에 빠진 Main 스레드 콜스택

 	mscorlib.dll!System.IO.TextWriter.SyncTextWriter.WriteLine(bool value)  Unknown No symbols loaded.
    mscorlib.dll!System.Console.WriteLine(bool value)   Unknown No symbols loaded.
>    ConsoleApp1.exe!ConsoleApp1.Program.Main(string[] args) Line 22 C#  Symbols loaded.

// Suspend된 t1 스레드의 콜스택
    [Managed to Native Transition]      Annotated Frame
    mscorlib.dll!System.IO.__ConsoleStream.WriteFileNative(Microsoft.Win32.SafeHandles.SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs) Unknown No symbols loaded.
    mscorlib.dll!System.IO.__ConsoleStream.Write(byte[] buffer, int offset, int count)  Unknown No symbols loaded.
    mscorlib.dll!System.IO.StreamWriter.Flush(bool flushStream, bool flushEncoder)  Unknown No symbols loaded.
    mscorlib.dll!System.IO.StreamWriter.Write(char[] buffer, int index, int count)  Unknown No symbols loaded.
    mscorlib.dll!System.IO.TextWriter.WriteLine(string value)   Unknown No symbols loaded.
    mscorlib.dll!System.IO.TextWriter.SyncTextWriter.WriteLine(string value)    Unknown No symbols loaded.
    mscorlib.dll!System.Console.WriteLine(string value) Unknown No symbols loaded.
>    ConsoleApp1.exe!ConsoleApp1.Program.threadFunc(object obj) Line 30  C#  Symbols loaded.
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)    Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart(object obj)  Unknown No symbols loaded.

SyncTextWriter 타입의 메서드들은 대부분 "[MethodImpl(MethodImplOptions.Synchronized)]" 특성이 적용되므로 단일 스레드에서만 독점 사용할 수 있습니다. 따라서 t1 스레드가 SyncTextWriter.WriteLine으로 먼저 진입해서 쓰고 있는 중에 Suspend가 되었고 Main 스레드에서는 다시 Console.WriteLine 호출로 인한 SyncTextWriter.WriteLine 진입 시도로 hang 상태에 빠진 것입니다.

즉, t.IsAlive 값을 못 구해온 것이 아니고 콘솔 출력에 대한 lock이 걸린 것입니다.

다시 말해서, 콘솔 출력 중인 다수의 스레드가 있을때 특정 스레드가 Suspend되면 다른 스레드들의 콘솔 출력에 모두 hang이 걸릴 수 있으니 주의해야 합니다.




비슷한 이유로 화면 출력이 hang 상태로 빠지는 경우가 있습니다.

static void Main(string[] args)
{
    while (true)
    {
        Thread t = new Thread(threadFunc);
        t.Start(i);
        Console.WriteLine(t.IsAlive);
        t.Suspend();
        Console.WriteLine(t.IsAlive); // 실행 정지
        t.Resume();
        t.Join();
    }
}

private static void threadFunc(object obj)
{
    Console.WriteLine("TEST: " + obj);
}

// 화면 출력 상태
True

즉, threadFunc의 Console.WriteLine이 호출되지 않은 듯 한데 Main 스레드의 Console.WriteLine에서 멈춘 것입니다. 역시 이유는 간단하게 호출 스택을 보면 알 수 있습니다.

// Suspend된 t1 스레드의 콜스택
    mscorlib.dll!System.IO.StreamWriter.Write(char[] buffer, int index, int count)  Unknown No symbols loaded.
    mscorlib.dll!System.IO.TextWriter.WriteLine(string value)   Unknown No symbols loaded.
    mscorlib.dll!System.IO.TextWriter.SyncTextWriter.WriteLine(string value)    Unknown No symbols loaded.
    mscorlib.dll!System.Console.WriteLine(string value) Unknown No symbols loaded.
>    ConsoleApp1.exe!ConsoleApp1.Program.threadFunc(object obj) Line 30  C#  Symbols loaded.
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)    Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown No symbols loaded.
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart(object obj)  Unknown No symbols loaded.

SyncTextWriter.WriteLine까지 진입해서 lock은 획득했으나 화면에 쓰려는 찰나 Suspend로 인해 스레드 실행이 멈춰 버린 것입니다.




또 다른 hang 사례를 보겠습니다.

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        while (true)
        {
            i++;
            Thread t = new Thread(threadFunc);
            t.Start(i);

            bool alive = t.IsAlive;
            if (alive == true)
            {
                t.Suspend();
            }

            alive = t.IsAlive;
            if (alive == true)
            {
                t.Resume();
            }
            t.Join();
        }
    }

    private static void threadFunc(object obj)
    {
        Console.WriteLine("TEST: " + obj);
    }
}

위와 같이 테스트해보면 어느 순간 hang에 걸리는 것을 볼 수 있습니다. 이때의 Main 스레드 콜스택을 보면 t.Join에서 멈춰 있습니다.

    mscorlib.dll!System.Threading.Thread.Join() Unknown No symbols loaded.
>    ConsoleApp1.exe!ConsoleApp1.Program.Main(string[] args) Line 33 C#  Symbols loaded.

반면 t1 스레드 자체는 이미 종료되어 콜 스택이 없습니다. 즉, 제대로 스레드가 종료된 이후에 호출되는 Join도 hang 상태에 빠져버리므로 Join에는 반드시 timeout 설정을 하는 것이 좋습니다.




이제 코드를 안정화시켜 보겠습니다.

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        while (true)
        {
            i++;
            Thread t = new Thread(threadFunc);
            t.Start(i);

            bool alive = t.IsAlive;
            if (alive == true)
            {
                t.Suspend();
            }

            alive = t.IsAlive;
            if (alive == true)
            {
                t.Resume();
            }
            t.Join(1000);
        }
    }

    private static void threadFunc(object obj)
    {
        Console.WriteLine("TEST: " + obj);
    }
}

실행해 보면, 다음과 같은 식으로 오류가 발생하는 경우가 있습니다.

TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 6
TEST: 7
TEST: 8
TEST: 9

Unhandled Exception: System.Threading.ThreadStateException: Thread is not running; it cannot be suspended.
   at System.Threading.Thread.SuspendInternal()
   at System.Threading.Thread.Suspend()
   at ConsoleApp1.Program.Main(String[] args)

즉, t.IsAlive로 체크할 당시만 해도 살아있던 t 스레드가 t.Suspend를 호출하는 사이 종료된 것입니다. 따라서 Suspend에 대해 try/catch를 하는 것이 좋습니다.

결국 Suspend/Resume/Join에 대한 안정적인 코드는 다음과 같습니다.

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        while (true)
        {
            i++;
            Thread t = new Thread(threadFunc);
            t.Start(i);

            bool alive = t.IsAlive;
            if (alive == true)
            {
                try
                {
                    t.Suspend();
                } catch { }
            }

            alive = t.IsAlive;
            if (alive == true)
            {
                try
                {
                    t.Resume();
                } catch { }

                t.Join(1000);
            }
        }
    }

    private static void threadFunc(object obj)
    {
        Console.WriteLine("TEST: " + obj);
    }
}

규칙은 간단합니다.

  1. Suspend와 Resume 호출은 반드시 try/catch를 해주고,
  2. Join은 timeout 설정을 한다.(음... 불안한데 Join도 try/catch를 해야 할까요? ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/23/2017]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12702정성태7/11/20218724오류 유형: 733. TaskScheduler에 등록된 wacs.exe의 Let's Encrypt 인증서 업데이트 문제
12701정성태7/9/20218360.NET Framework: 1075. C# - ThreadPool의 스레드는 반환 시 ThreadStatic과 AsyncLocal 값이 초기화 될까요?파일 다운로드1
12700정성태7/8/20218778.NET Framework: 1074. RuntimeType의 메모리 누수? [1]
12699정성태7/8/20217555VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202111523오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/20217413개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/20217967VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
12695정성태7/3/20218029VC++: 145. C 언어의 setjmp/longjmp 기능을 Thread Context를 이용해 유사하게 구현하는 방법파일 다운로드1
12694정성태7/2/20219937Java: 24. Azure - Spring Boot 앱을 Java SE(Embedded Web Server)로 호스팅 시 로그 파일 남기는 방법 [1]
12693정성태6/30/20217715오류 유형: 731. Azure Web App Site Extension - Failed to install web app extension [...]. {1}
12692정성태6/30/20217590디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/20218458개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/20219264Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
12689정성태6/25/20219806오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
12688정성태6/24/20219504.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen [2]파일 다운로드1
12687정성태6/22/20217519오류 유형: 729. Invalid data: Invalid artifact, java se app service only supports .jar artifact
12686정성태6/21/20219940Java: 22. Azure - 자바(Java)로 만드는 Web App Service - Java SE (Embedded Web Server) 호스팅
12685정성태6/21/202110157Java: 21. Azure Web App Service에 배포된 Java 프로세스의 메모리 및 힙(Heap) 덤프 뜨는 방법
12684정성태6/19/20218615오류 유형: 728. Visual Studio 2022부터 DTE.get_Properties 속성 접근 시 System.MissingMethodException 예외 발생
12683정성태6/18/202110122VS.NET IDE: 166. Visual Studio 2022 - Windows Forms 프로젝트의 x86 DLL 컨트롤이 Designer에서 오류가 발생하는 문제 [1]파일 다운로드1
12682정성태6/18/20217803VS.NET IDE: 165. Visual Studio 2022를 위한 Extension 마이그레이션
12681정성태6/18/20217128오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/20218237오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/20218858COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/20218085.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219571VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...