Microsoft MVP성태의 닷넷 이야기
.NET Framework: 926. C# - ETW를 이용한 ThreadPool 스레드 감시 [링크 복사], [링크+제목 복사],
조회: 9739
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 2개 있습니다.)
.NET Framework: 651. C# - 특정 EXE 프로세스를 종료시킨 EXE를 찾아내는 방법
; https://www.sysnet.pe.kr/2/0/11172

.NET Framework: 926. C# - ETW를 이용한 ThreadPool 스레드 감시
; https://www.sysnet.pe.kr/2/0/12260




C# - ETW를 이용한 ThreadPool 스레드 감시

ETW를 이용해 ThreadPool을 감시하는 것은 1) Worker 스레드를 위한 ThreadPoolWorkerThreadStart, ThreadPoolWorkerThreadStop 이벤트와 2) I/O 스레드를 위한 IOThreadCreationStart, IOThreadCreationStop 이벤트를 구독하면 됩니다.

using (var session = new TraceEventSession(sessionName, null))
{
    var restarted = session.EnableProvider(
        ClrTraceEventParser.ProviderGuid, TraceEventLevel.Verbose,
        (ulong)(ClrTraceEventParser.Keywords.Threading));

    Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) { session.Dispose(); };

    using (TraceLogEventSource traceLogSource = TraceLog.CreateFromTraceEventSession(session))
    {
        traceLogSource.Clr.ThreadPoolWorkerThreadStart += delegate (ThreadPoolWorkerThreadTraceData data)
        {
            if (data.ProcessID != _processId)
            {
                return;
            }

            Console.WriteLine($"[{data.TimeStamp}] {data.ThreadID} Worker Start");
        };

        traceLogSource.Clr.ThreadPoolWorkerThreadStop += delegate (ThreadPoolWorkerThreadTraceData data)
        {
            if (data.ProcessID != _processId)
            {
                return;
            }

            Console.WriteLine($"[{data.TimeStamp}] {data.ThreadID} Worker Stop");
        };

        traceLogSource.Clr.IOThreadCreationStart += delegate (IOThreadTraceData data)
        {
            if (data.ProcessID != _processId)
            {
                return;
            }

            Console.WriteLine($"[{data.TimeStamp}] {data.ThreadID} IO Start");
        };

        traceLogSource.Clr.IOThreadCreationStop += delegate (IOThreadTraceData data)
        {
            if (data.ProcessID != _processId)
            {
                return;
            }

            Console.WriteLine($"[{data.TimeStamp}] {data.ThreadID} IO Stop");
        };

        traceLogSource.Process();
    }

    // ...[생략]...}
}

테스트할 수 있는 예제로 다음과 같이 Worker 스레드와 I/O 스레드를 사용하는 코드를 넣고,

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace TestApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Debug.Assert(ThreadPool.SetMinThreads(2, 1));
            Debug.Assert(ThreadPool.SetMaxThreads(4, 4)); // 4개로 제한

            Thread.Sleep(5000);
            Console.WriteLine(Process.GetCurrentProcess().Id);

            for (int i = 0; i < 4; i++) 
            {
                ThreadPool.QueueUserWorkItem(async (arg) =>
                {
                    // 이 코드는 닷넷 프레임워크 환경에서 테스트한 것입니다. (참고: 닷넷 런타임에 따라 달라지는 AppDomain.GetCurrentThreadId의 반환값)
                    Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} WorkerThread: " + arg);
                    await ReadFileAsync();
                    Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} WorkerThread: " + arg + ": End");
                }, i);
            }

            Console.ReadLine();
        }

        static async Task ReadFileAsync()
        {
            string filePath = typeof(Program).Assembly.Location;
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
            byte[] buf = new byte[1024];
            await fs.ReadAsync(buf, 0, buf.Length);

            fs.Dispose(); 
            Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} Done");
        }
    }
}

실행해 보면,

[2020-07-08 오전 9:04:02] 44576 3 WorkerThread: 0
[2020-07-08 오전 9:04:02] 27876 6 WorkerThread: 3
[2020-07-08 오전 9:04:02] 24556 5 WorkerThread: 2
[2020-07-08 오전 9:04:02] 11376 4 WorkerThread: 1
[2020-07-08 오전 9:04:02] 24556 5 Done
[2020-07-08 오전 9:04:02] 11376 4 Done
[2020-07-08 오전 9:04:02] 11376 4 WorkerThread: 0: End
[2020-07-08 오전 9:04:02] 11376 4 Done
[2020-07-08 오전 9:04:02] 11376 4 WorkerThread: 2: End
[2020-07-08 오전 9:04:02] 27876 6 Done
[2020-07-08 오전 9:04:02] 27876 6 WorkerThread: 3: End
[2020-07-08 오전 9:04:02] 24556 5 WorkerThread: 1: End

위의 상황에 대한 ETW 모니터링 결과가 다소 실망스럽습니다.

[2020-07-08 오전 9:04:02] 44576 Worker Start
[2020-07-08 오전 9:04:02] 11376 Worker Start
[2020-07-08 오전 9:04:02] 24556 Worker Start
[2020-07-08 오전 9:04:02] 27876 Worker Start
[2020-07-08 오전 9:04:02] 11376 IO Start
[2020-07-08 오전 9:04:02] 24556 IO Start
[2020-07-08 오전 9:04:02] 44576 IO Start
[2020-07-08 오전 9:04:17] 55484 IO Stop
[2020-07-08 오전 9:04:17] 53212 IO Stop
[2020-07-08 오전 9:04:22] 44576 Worker Stop
[2020-07-08 오전 9:04:22] 24556 Worker Stop
[2020-07-08 오전 9:04:22] 27876 Worker Stop
[2020-07-08 오전 9:04:22] 11376 Worker Stop

보는 바와 같이 IO Start/Stop의 짝이 안 맞을뿐더러, 테스트 코드를 약간 바꿔서,

static async Task Main(string[] args)
{
    Debug.Assert(ThreadPool.SetMinThreads(2, 1));
    Debug.Assert(ThreadPool.SetMaxThreads(4, 4)); // 4개로 제한

    Thread.Sleep(5000);
    Console.WriteLine(Process.GetCurrentProcess().Id);

    for (int i = 0; i < 4; i++) 
    {
        ThreadPool.QueueUserWorkItem(async (arg) =>
        {
            Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} WorkerThread: " + arg);
            ReadFile();
            Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} WorkerThread: " + arg + ": End");
        }, i);
    }

    Console.ReadLine();
}

static void ReadFile()
{
    string filePath = typeof(Program).Assembly.Location;
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
    byte[] buf = new byte[1024];

    fs.BeginRead(buf, 0, buf.Length, (obj) =>
    {
        IAsyncResult result = obj as IAsyncResult;
        fs.EndRead(result);

        fs.Dispose();
        Console.WriteLine($"[{DateTime.Now}] {AppDomain.GetCurrentThreadId()} {Thread.CurrentThread.ManagedThreadId} Done");
    }, fs);
}

실행해 보면, BeginRead의 콜백 메서드가 출력한 I/O 스레드의 thread id가,

[2020-07-08 오전 9:18:13] 9180 5 WorkerThread: 1
[2020-07-08 오전 9:18:13] 38904 6 WorkerThread: 2
[2020-07-08 오전 9:18:13] 20752 4 WorkerThread: 3
[2020-07-08 오전 9:18:13] 53232 3 WorkerThread: 0
[2020-07-08 오전 9:18:13] 38904 6 WorkerThread: 2: End
[2020-07-08 오전 9:18:13] 20752 4 WorkerThread: 3: End
[2020-07-08 오전 9:18:13] 9180 5 WorkerThread: 1: End
[2020-07-08 오전 9:18:13] 53232 3 WorkerThread: 0: End
[2020-07-08 오전 9:18:13] 20752 4 Done
[2020-07-08 오전 9:18:13] 20752 4 Done
[2020-07-08 오전 9:18:13] 53232 3 Done
[2020-07-08 오전 9:18:13] 9180 5 Done

ETW 모니터링의 IO Stop 이벤트에서는 연결이 안 됩니다.

[2020-07-08 오전 9:18:13] 53232 Worker Start
[2020-07-08 오전 9:18:13] 9180 Worker Start
[2020-07-08 오전 9:18:13] 38904 Worker Start
[2020-07-08 오전 9:18:13] 20752 Worker Start
[2020-07-08 오전 9:18:13] 9180 IO Start
[2020-07-08 오전 9:18:13] 20752 IO Start
[2020-07-08 오전 9:18:13] 38904 IO Start
[2020-07-08 오전 9:18:13] 53232 IO Start
[2020-07-08 오전 9:18:28] 3664 IO Stop
[2020-07-08 오전 9:18:28] 13716 IO Stop
[2020-07-08 오전 9:18:28] 3980 IO Stop
[2020-07-08 오전 9:18:33] 38904 Worker Stop
[2020-07-08 오전 9:18:33] 9180 Worker Stop
[2020-07-08 오전 9:18:33] 53232 Worker Stop
[2020-07-08 오전 9:18:33] 20752 Worker Stop

위의 결과만으로는, IO Start와 IO Stop의 정보를 연결할 단서가 없어 모니터링으로써의 효과가 거의 없습니다. 그래도 일단 이번에는 여기까지라도 알아두고. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 4/7/2022]

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)
12771정성태8/11/20218176Windows: 196. "Microsoft Windows Subsystem for Linux Background Host" / "Vmmem"을 종료하는 방법
12770정성태8/11/20218968.NET Framework: 1086. C# - Windows Forms 응용 프로그램의 자식 컨트롤 부하파일 다운로드1
12769정성태8/11/20216770오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main 두 번째 이야기
12768정성태8/10/20217864.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [1]파일 다운로드1
12767정성태8/10/20218925오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main
12766정성태8/9/20217383Java: 32. closing inbound before receiving peer's close_notify
12765정성태8/9/20216738Java: 31. Cannot load JDBC driver class 'org.mysql.jdbc.Driver'
12764정성태8/9/202145210Java: 30. XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid
12763정성태8/9/20218231Java: 29. java.lang.NullPointerException - com.mysql.jdbc.ConnectionImpl.getServerCharset
12762정성태8/8/202111753Java: 28. IntelliJ - Unable to open debugger port 오류
12761정성태8/8/20218898Java: 27. IntelliJ - java: package javax.inject does not exist [2]
12760정성태8/8/20216234개발 환경 구성: 594. 전용 "Command Prompt for ..." 단축 아이콘 만들기
12759정성태8/8/20219480Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [2]파일 다운로드1
12758정성태8/7/20218804오류 유형: 751. Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
12757정성태8/7/20219512Java: 25. IntelliJ + Spring Framework 프로젝트 생성
12756정성태8/6/20218266.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법 [1]파일 다운로드1
12755정성태8/5/20217459개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법파일 다운로드1
12754정성태8/5/20218330오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218567오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216653개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/20219725개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216515디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20215929개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216570개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20217136오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/20219171개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...