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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11099정성태11/7/201630697.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201620053오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201622975오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201626789디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201623050.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201624666VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201624580웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201631563.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201626318VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201627772VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201626662디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201630727.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625175.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201618980오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201633355.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201621396오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201627893Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201629826.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201620330오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201623510Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201620633Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201621909Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201620403오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201620018오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201620982Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
11074정성태10/20/201629279Windows: 126. Windows Server 2016 평가판을 정식 버전으로 라이선스 변경하는 방법
... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...