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)
12742정성태7/30/20217209개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20218358.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217055오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217014오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20217588오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216553오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217043오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217546.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123487스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202110897.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216227오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217314개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20218852개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20217846.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/20217326.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/20218267.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/20218096VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/20216872오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/20219512개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/20217138오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/20217011오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/20217626오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/20216963Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/20216117오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/20216702개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/20216723Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...