Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 3개 있습니다.)
.NET Framework: 547. PerformanceCounter의 InstanceName 지정 시 주의 사항
; https://www.sysnet.pe.kr/2/0/10898

Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
; https://www.sysnet.pe.kr/2/0/13585

닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법
; https://www.sysnet.pe.kr/2/0/13891




C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법

성능 카운터의 InstanceName은 기본적으로 프로세스 이름으로 정해집니다. 가령 test.exe라는 실행 파일이면 성능 카운터의 InstanceName도 "test.exe"입니다. 하지만 동일한 이름의 프로세스가 여러 개 실행되는 경우에는 개별 인스턴스를 구분하기 위해 "#1", "#2"와 같은 접미사가 붙습니다. 즉, "test.exe"라는 프로세스를 3개 실행하면 InstanceName은 "test.exe", "test.exe#1", "test.exe#2"가 됩니다.

그런데 문제는, 저 InstanceName이 실행 중에도 변경될 수 있다는 것입니다. 가령, test.exe가 다음과 같이 실행 중일 때,

test.exe PID == 1000, InstanceName == test.exe
test.exe PID == 2000, InstanceName == test.exe#1
test.exe PID == 3000, InstanceName == test.exe#2

저 상태에서 PID == 2000인 test.exe가 종료되면 이제 InstanceName은 이렇게 바뀝니다.

test.exe PID == 1000, InstanceName == test.exe
test.exe PID == 3000, InstanceName == test.exe#1

이런 문제를 PerformanceCounterCategory.GetInstanceNames() + PerformanceCounter.RawValue 코드를 매번 수행하는 식으로 해결해야 한다고 설명한 것이 아래의 글입니다.

PerformanceCounter의 InstanceName 지정 시 주의 사항
; https://www.sysnet.pe.kr/2/0/10898

재미있는 건, 저 과정에서도 시점의 차이로 인해 오류가 발생할 수 있습니다. 가령, 다음과 같이 GetInstanceNames()를 호출한 다음,

var category = new PerformanceCounterCategory("Process");
var instanceNames = category.GetInstanceNames().Where(x => x.Contains(proc.ProcessName));
// 위의 호출을 한 시기에 test.exe, test.exe#1, test.exe#2가 존재했다고 가정

이후 코드에서 instanceNames 배열의 이름으로 성능 카운터를 구하려는 시점까지의 상황 변화로 인해 예외가 발생할 수 있습니다.

string[] instances = ...[생략: GetInstanceNames()]...;

// 하지만, 아래의 코드를 호출하는 동안 "test.exe#1"이 종료했다면?

foreach (string instance in instances)
{
    using (PerformanceCounter cnt = new PerformanceCounter(categoryName,
            "Process ID", instance, true))
    {
        int val = 0;

        try
        {
            // 시점에 따라 예외 발생
            // Unhandled exception. System.InvalidOperationException: Instance 'RuntimeBroker#10' does not exist in the specified Category.
            //    at System.Diagnostics.PerformanceCounter.NextSample()
            //    at System.Diagnostics.PerformanceCounter.get_RawValue()
            //    ...[생략]...
            val = (int)cnt.RawValue; // 또는, "카운터는 단일 인스턴스가 아니며 인스턴스 이름을 지정해야 합니다." 오류 발생        
        }
        catch
        {
            continue;
        }

        if (val == pid)
        {
            return instance;
        }
    }
}

실제로 저런 경우는 다반사로 발생할 수 있습니다. 지난 글에서도 GetInstanceNames 자체는 25ms가 소요되지만, 이후 개별 instanceName마다 "ID Process"를 이용한 PerformanceCounter.RawValue를 가져오는 데 25ms가 걸린다고 했습니다.

결국, (보통 수십 개의 프로세스가 뜨는) svchost.exe의 경우에는 instanceName마다 25ms가 걸리기 때문에 만약 50개의 svchost.exe가 실행 중이라면 하필 마지막 인스턴스까지 열거하는 경우 1.25초가 걸릴 수 있습니다. 따라서 그 사이에 얼마든지 svchost.exe의 생성/소멸이 발생할 수 있기 때문에 오류를 겪을 가능성이 적지 않게 됩니다.

게다가, 설령 그렇게 해서 instanceName을 결정해도 이후 그 InstanceName을 가지고 본격적인 성능 카운터를 구하려고 할 텐데, 그 시점까지 고려한다면 더욱더 오류가 발생할 수 있는 가능성이 높아집니다.




물론, 저런 문제를 "Process V2" 범주에서는 단순히 "[프로세스명]:[프로세스ID]"로 instanceName을 정할 수 있으니 GetInstanceNames() + PerformanceCounter.RawValue 단계를 거칠 필요가 없습니다.

하지만, "[프로세스명]:[프로세스ID]" 형식은 Windows 11/Windows Server 2022 버전부터 제공하는데다, 그나마도 오직 Process V2 범주만을 지원하기 때문에 다른 성능 카운터를 가져와야 하는 경우라면 여전히 "[프로세스명]#[순서]" 작명을 써야 합니다.

재미있게도 지난 글의 WMI 클래스인 Win32_PerfRawData_PerfProc_Process를 보면서 이것을 구할 수 있는 또 다른 방법을 찾았습니다. ^^

왜냐하면 Win32_PerfRawData_PerfProc_Process의 Name이 바로 "[프로세스명]#[순서]"로 돼 있기 때문입니다. 그래서, 이제 아래와 같은 방법으로도 InstanceName을 구할 수 있습니다.

using System.Diagnostics;
using System.Management;

[assembly: System.Runtime.Versioning.SupportedOSPlatform("windows")]

internal class Program
{
    static void Main(string[] args)
    {
        foreach (var process in Process.GetProcesses())
        {
            string instanceName = GetInstanceName((uint)process.Id);
            Console.WriteLine($"Process: {process.ProcessName}, InstanceName: {instanceName}");
        }
    }

    static string GetInstanceName(uint pid)
    {
        string query = $"SELECT Name FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess = {pid}";

        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", query))
        using (var data = searcher.Get())
        using (var e = data.GetEnumerator())
        {
            e.MoveNext();
            if (e.Current == null)
            {
                return "";
            }

            return (string)e.Current.Properties["Name"].Value;
        }
    }
}

실행 속도는 어떨까요? ^^ 이게 좀 아쉽습니다. 위의 코드를 한번 실행하는데 제 컴퓨터 기준으로 70 ~ 100ms 정도 걸렸는데요, 단일 프로세스에 대해 GetInstanceNames() + PerformanceCounter.RawValue 방식이 25ms + 25ms 정도 걸리는 것에 비하면 더 느린 결과를 보여줍니다.

대신, 다중 프로세스(svchost.exe 등)에 대해서는 프로세스가 몇 개냐에 상관없이 일관되게 그 속도를 내주기 때문에 GetInstanceNames() + PerformanceCounter.RawValue 방식이 25ms + 1,250ms 정도 걸렸을 때와 비교하면 빠른 결과를 내주기도 합니다. 도대체가 은 탄환이 없군요. ^^;

그냥 InstanceName을 구하는 또 다른 방법을 알았다는 것과, 만약 프로세스 수가 많은 경우라면 WMI를 이용한 것도 괜찮을 거라는 정도만 알고 넘어가면 되겠습니다. ^^

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




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







[최초 등록일: ]
[최종 수정일: 2/23/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  [82]  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11886정성태5/7/201919251오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/201916186오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201920984.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201926210.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201922466.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201922598오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201918446오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201926843.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
11878정성태4/22/201922585.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff파일 다운로드1
11877정성태4/22/201922666.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas파일 다운로드1
11876정성태4/21/201921709.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others파일 다운로드1
11875정성태4/21/201922711오류 유형: 530. Visual Studo에서 .NET Core 프로젝트를 열 때 "One or more errors occurred." 오류 발생
11874정성태4/20/201922912.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals파일 다운로드1
11873정성태4/19/201921370.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers파일 다운로드1
11872정성태4/17/201922252.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members파일 다운로드1
11871정성태4/16/201920924.NET Framework: 818. (번역글) .NET Internals Cookbook Part 3 - Initialization tricks [3]파일 다운로드1
11870정성태4/16/201919182.NET Framework: 817. Process.Start로 실행한 콘솔 프로그램의 출력 결과를 얻는 방법파일 다운로드1
11869정성태4/15/201925009.NET Framework: 816. (번역글) .NET Internals Cookbook Part 2 - GC-related things [2]파일 다운로드2
11868정성태4/15/201921007.NET Framework: 815. CER(Constrained Execution Region)이란?파일 다운로드1
11867정성태4/15/201920127.NET Framework: 814. Critical Finalizer와 SafeHandle의 사용 의미파일 다운로드1
11866정성태4/9/201923306Windows: 159. 네트워크 공유 폴더(net use)에 대한 인증 정보는 언제까지 유효할까요?
11865정성태4/9/201919031오류 유형: 529. 제어판 - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools is not accessible.
11864정성태4/9/201917809오류 유형: 528. '...' could be '0': this does not adhere to the specification for the function '...'
11863정성태4/9/201917668디버깅 기술: 127. windbg - .NET x64 EXE의 EntryPoint
11862정성태4/7/201920147개발 환경 구성: 437. .NET EXE의 ASLR 기능을 끄는 방법
11861정성태4/6/201919611디버깅 기술: 126. windbg - .NET x86 CLR2/CLR4 EXE의 EntryPoint
... 76  77  78  79  80  81  [82]  83  84  85  86  87  88  89  90  ...