Microsoft MVP성태의 닷넷 이야기
.NET Framework: 676. C# Thread가 Running 상태인지 아는 방법 [링크 복사], [링크+제목 복사],
조회: 30004
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# Thread가 Running 상태인지 아는 방법

Thread가 실행 상태인지 어떻게 알 수 있을까요? 가령 Thread.IsAlive가 왠지 그럴 것 같습니다. 테스트를 해볼까요?

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(threadFunc);
        t.Start();

        bool alive = t.IsAlive;
        Console.WriteLine(alive);
    }

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

위의 코드에서 Console.WriteLine에 BP를 걸고 비주얼 스튜디오를 시작한 후 Ctrl+Alt+H 단축키를 눌러 Threads 창을 띄우면 결과를 알 수 있습니다. t.IsAlive는 true이지만 t 스레드는 생성조차 되지 않은 것을 볼 수 있습니다. 즉 t.IsAlive는 Thread 객체가 생성된 후 Start 메서드가 불린 순간부터 무조건 true이고 그 이후 스레드 종료가 되어야 false로 바뀌는 것입니다.




다음 후보로 Thread.ThreadState는 어떨까요? ThreadState enum 값에는 분명히 Running이 있으니 다음과 같이 테스트할 수 있습니다.

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(threadFunc);
        t.Start();

        bool alive = t.IsAlive;
        bool running = t.ThreadState == ThreadState.Running;
        Console.WriteLine(alive);
    }

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

그런데 이것 역시 BP를 걸어 테스트해보면 실제 스레드 생성 유무와 상관없이 Thread.Start 이후 Running 상태임을 알 수 있습니다. 설령 이 필드가 그 의미 그대로 Running이라고 해도 문제입니다. 왜냐하면 필드의 값이 0이기 때문입니다.

[ComVisible(true)]
[Flags]
public enum ThreadState
{
    Running = 0,
    StopRequested = 1,
    SuspendRequested = 2,
    Background = 4,
    Unstarted = 8,
    Stopped = 16,
    WaitSleepJoin = 32,
    Suspended = 64,
    AbortRequested = 128,
    Aborted = 256
}

따라서 Thread.IsBackground = true; 같은 식으로 설정해 버리면 Running을 알아낼 방법이 없습니다. 왜냐하면 다음의 조건도 false이고,

bool running = t.ThreadState == ThreadState.Running; // ThreadState == 4 (Background)이므로.

그렇다고 다음과 같이 해도 Running이 0이므로 항상/무조건 true가 나옵니다.

bool running = (t.ThreadState & ThreadState.Running) == ThreadState.Running;




결국 가장 적당한 방법은 스레드 함수가 실행하는 초기/후기에 EventWaitHandle 등을 이용해 그 사실을 알려주는 것입니다.

static void Main(string[] args)
{
    EventWaitHandle started = new EventWaitHandle(false, EventResetMode.ManualReset);
    EventWaitHandle exited = new EventWaitHandle(false, EventResetMode.ManualReset);
    Thread t = new Thread(threadFunc);

    t.Start((started, exited));

    bool threadStarted = started.WaitOne(0);
    bool threadExited = exited.WaitOne(0);
}

private static void threadFunc(object obj)
{
    var events = (System.ValueTuple<EventWaitHandle, EventWaitHandle>)obj;
    {
        events.Item1.Set();

        Console.WriteLine("TEST: " + obj);

        events.Item2.Set();
    }
}

또는 DONT_USE_InternalThread 등의 내부 필드를 이용해,

.NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까?
; https://www.sysnet.pe.kr/2/0/1244

그에 상응하는 스레드를 Process.GetCurrentProcess().Threads에서 찾는 방식을 비공식적으로 고려할 수 있습니다.




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







[최초 등록일: ]
[최종 수정일: 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)
13868정성태1/17/20253109Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20254046오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20254261개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20253941오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20253905Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20253356Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20253616Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20253907Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20253599디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20253955디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20254100개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20254137C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20253726디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20244445오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20244543C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244023디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20244470디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20244228디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20244725오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20244876디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20244817디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20244840오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20245052디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20244526디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20245210디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20244381오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...