Microsoft MVP성태의 닷넷 이야기
.NET Framework: 676. C# Thread가 Running 상태인지 아는 방법 [링크 복사], [링크+제목 복사],
조회: 30102
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11382정성태12/4/201721847오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718227.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718276디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719005오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720471.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719709.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724064VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201718902오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201723971사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201722974오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726013사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719649오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719531오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721661사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727247.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727304개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201718950오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721212오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723088사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723068사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719602오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722408오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722192오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721676오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726437사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201726878개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...