Microsoft MVP성태의 닷넷 이야기
.NET Framework: 674. Thread 타입의 Suspend/Resume/Join 사용 관련 예외 처리 [링크 복사], [링크+제목 복사],
조회: 12572
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13114정성태8/2/20228699.NET Framework: 2039. C# - Task와 비교해 본 ValueTask 사용법파일 다운로드1
13113정성태7/31/20227936.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
13112정성태7/30/20228338.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [1]파일 다운로드1
13111정성태7/29/20228097.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합파일 다운로드1
13110정성태7/27/20228143.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)파일 다운로드1
13109정성태7/27/20229605VS.NET IDE: 177. 비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)" [1]
13108정성태7/26/20227547Linux: 53. container에 실행 중인 Golang 프로세스를 디버깅하는 방법 [1]
13107정성태7/25/20226738Linux: 52. Debian/Ubuntu 계열의 docker container에서 자주 설치하게 되는 명령어
13106정성태7/24/20226429오류 유형: 819. 닷넷 6 프로젝트의 "Conditional compilation symbols" 기본값 오류
13105정성태7/23/20227733.NET Framework: 2034. .NET Core/5+ 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 - 두 번째 이야기 [1]
13104정성태7/23/202210834Linux: 51. WSL - init에서 systemd로 전환하는 방법
13103정성태7/22/20227341오류 유형: 818. WSL - systemd-genie와 관련한 2가지(systemd-remount-fs.service, multipathd.socket) 에러
13102정성태7/19/20226761.NET Framework: 2033. .NET Core/5+에서는 구할 수 없는 HttpRuntime.AppDomainAppId
13101정성태7/15/202215696도서: 시작하세요! C# 10 프로그래밍
13100정성태7/15/20228139.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
13099정성태7/14/20228015.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/20226217개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/20225605오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228507.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226573Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226316오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20227200.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20228182.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226992.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20226148오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226592개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...