2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

강의자료/C#

[C#] PerformanceCounter 를 활용하여 작업관리자 구현

원당컴1 2020. 12. 16. 12:42
목표

- Windows NT의 성능 구성 요소를 나타내는 PerformanceCounter 사용법을 배운다.

- 쓰레드의 사용법을 배운다.

- 델리게이트의 사용법을 배운다 (jeong-pro.tistory.com/51)

 

 

컴포넌트설명

StatusStrip : 상태 표시줄로 메시지, 진행상태등을 표현한다.

 

폼구성

1.ListView 를 추가하여 위와 같이 이름,PID,Time,메모리 를 추가한다.

2. Button, StatusStrip 을 추가하여 위와 같이 화면 구성

 

소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WorkManager
{
    public partial class Form1 : Form
    {
        int processCount = 0;
        private Thread ProcessThread; //프로세스 보여주기 위한 쓰레드
        Thread checkThread = null;    //실시간 시스템 정보 체크하기 위한 쓰레드
 
        private delegate void UpdateProcessDelegate(); //프로세스 현재 상태를 업데이트 하기 위한 델리게이트 생성
        private UpdateProcessDelegate updateProcess = null;
 
        private delegate void UpdateTotalDelegate(int m,int n); //status Bar에 성능 표시
        private UpdateTotalDelegate updateTotal = null;
 
        private PerformanceCounter oCpu = new PerformanceCounter("Processor""% Processor Time""_Total"); //시스템 CPU성능 카운터
        /*PerformanceCounter 사용법 
         * 첫번째 인자 Performance Object (IP,Processor,WMI,Memory
         * 두번째 인자 해당 Object의 카운터(Processor 인 경우 % Processor Time,% User Time, Thread Count)
         * (Memory 인 경우 Available MByte,Available KByte
         * 세번째 인자 프로세스의 이름
         * cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); //new PerformanceCounter("Processor", "% Processor Time", appName);
         * ramCounter = new PerformanceCounter("Memory", "Available MBytes");
         */
        private PerformanceCounter oMem =
            new PerformanceCounter("Memory""% Committed Bytes In Use"); //시스템 Mem 성능 카운터
        private PerformanceCounter pCPU =
            new PerformanceCounter();
 
        bool bExit = false;
 
        public Form1()
        {
            InitializeComponent();
        }
        private void ProcessView()
        {
            try
            {
                this.lvView.Items.Clear();
                processCount = 0;
                foreach (var proc in Process.GetProcesses()) //모든 프로세스의 목록을 가져 오자
                {
                    string[] str;
                    try
                    {
                        str = proc.UserProcessorTime.ToString().Split(new Char[] { '.' });
                        //str = proc.TotalProcessorTime.ToString().Split(new Char[] { '.' }); //프로세스의 총시간
                    }
                    catch { str = new string[] { "" }; }
 
                    var strArray = new string[] { proc.ProcessName.ToString(), proc.Id.ToString(), //프로세스이름, 아이디
                        str[0], NumFormat(proc.WorkingSet64) }; //프로세스  수행시간,메모리 점유율
 
                    var lvt = new ListViewItem(strArray);
                    this.lvView.Items.Add(lvt);
                    processCount++;
                }
            }
            catch { }
            this.tssProcess.Text = "프로세스 : " + processCount.ToString() + "개";
        }
 
        private string NumFormat(long MemNum)
        {
            MemNum = MemNum / 1024;
            return String.Format("{0:N}", MemNum) + " KB"//N은 숫자 서식 지정자 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            ProcessView(); //프로세스 출력
            updateProcess = new UpdateProcessDelegate(ProcessView); //ProcessView 델리게이트
            updateTotal = new UpdateTotalDelegate(TotalView);
            ProcessThread = new Thread(ProcessUpdate); //스레드 대리자에 구동 메서드 입력
            ProcessThread.Start(); //스레드 시작
            checkThread = new Thread(getCPU_Info);
            checkThread.Start();
        }
 
        private void getCPU_Info()
        {
            try
            {
                while (!bExit)
                {
                    int iCPU = (int)oCpu.NextValue();
                    int iMem = (int)oMem.NextValue();
                    Invoke(updateTotal, iCPU, iMem);
                    Thread.Sleep(1000);
                }
            }
            catch { }
        }
 
        private void ProcessUpdate()
        {
            try
            {
                while (true)
                {
                    //Invoke(updateProcess);
                   // Thread.Sleep(1000);
                   // continue;
                    var oldlist = new ArrayList();
                    foreach (var oldproc in Process.GetProcesses())
                    {
                        oldlist.Add(oldproc.Id.ToString());
                    }
                    Thread.Sleep(1000);
                    var newproc = Process.GetProcesses();
                    if (oldlist.Count != newproc.Length)
                    {
                        Invoke(updateProcess);
                        continue;
                    }
                    int i = 0;
                    foreach (var rewproc in Process.GetProcesses())
                    {
                        if (oldlist[i++].ToString() != rewproc.Id.ToString())
                        {
                            Invoke(updateProcess);
                            break;
                        }
                    }
                }
            }
            catch { }
        }
 
        private void TotalView(int m, int n)
        {
            try
            {
                this.tssCpu.Text = "CPU 사용: " + m.ToString() + " %";
                this.tssMemory.Text = "실제 메모리 : " + n.ToString() + " %";
            }
            catch { }
        }
 
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            bExit = true;
            if (!(ProcessThread == null))
                ProcessThread.Abort(); //스레드 종료
            if (!(checkThread == null))
                checkThread.Abort(); //스레드 종료
        }
    }
}
 
cs

 

활용

시스템 정보를 활용하는 응용프로그램 구현

 

 

=====================================================

이 자료는 학생들과 특강시간에 프로젝트를 만들어 보는 프로젝트입니다.

=====================================================

 

오늘도 최선을 다하는 우리 학생들을 응원합니다.

 

인천 서구 검단신도시 원당컴퓨터학원

 

 

사업자 정보 표시
원당컴퓨터학원 | 기희경 | 인천 서구 당하동 1028-2 장원프라자 502호 | 사업자 등록번호 : 301-96-83080 | TEL : 032-565-5497 | Mail : icon001@naver.com | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기