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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13607정성태4/25/2024185닷넷: 2248.C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024198닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024341닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024376오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024695닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024801닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024848닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024869닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024867닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024889닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024877닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241064닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241051닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241069닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241084닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241219C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241198닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241079Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241154닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241267닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241170오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241334Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241115Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241065개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241303Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...