C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率
程序员文章站
2022-03-12 10:13:42
C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率 ......
c# 使用 performancecounter 获取 cpu 和 硬盘的使用率:
先看界面:
建一个 windows form 桌面程序,代码如下:
using system; using system.componentmodel; using system.windows.forms; using system.diagnostics; using system.threading; namespace performancecounterapp { public partial class mainform : form { private backgroundworker backgroundworker; private bool isworking = false; public mainform() { initializecomponent(); } private void form_load(object sender, eventargs e) { cpulabel.text = string.empty; disklabel.text = string.empty; backgroundworker = new backgroundworker(); backgroundworker.workerreportsprogress = true; backgroundworker.workersupportscancellation = true; backgroundworker.dowork += backgroundworker_dowork; backgroundworker.progresschanged += backgroundworker_progresschanged; backgroundworker.runworkercompleted += backgroundworker_runworkercompleted; } private void backgroundworker_dowork(object sender, doworkeventargs e) { //performancecounter diskp = new performancecounter("physicaldisk", "% disk time", "_total"); isworking = true; backgroundworker.reportprogress(0, "loading.../"); performancecounter cpup = new performancecounter("processor", "% processor time", "_total"); performancecounter diskp = new performancecounter("physicaldisk", "disk read bytes/sec", "_total"); try { do { thread.sleep(150); var cpuv1 = (int)cpup.nextvalue(); var diskv1 = (int)diskp.nextvalue(); thread.sleep(150); var cpuv2 = (int)cpup.nextvalue(); var diskv2 = (int)diskp.nextvalue(); thread.sleep(150); var cpuv3 = (int)cpup.nextvalue(); var diskv3 = (int)diskp.nextvalue(); thread.sleep(150); var cpuv4 = (int)cpup.nextvalue(); var diskv4 = (int)diskp.nextvalue(); var cpuv = (cpuv1 + cpuv2 + cpuv3 + cpuv4) / 4; var diskv = (diskv1 + diskv2+ diskv3 + diskv4) / 4; string data = $"{cpuv}%/{diskv}"; backgroundworker.reportprogress(0,data); } while (!backgroundworker.cancellationpending); } catch (exception) { throw; } finally { cpup.dispose(); diskp.dispose(); isworking = false; } } private void backgroundworker_progresschanged(object sender, progresschangedeventargs e) { string[] data = e.userstate.tostring().split('/'); cpulabel.text = $"cpu: {data[0]}"; disklabel.text = $"disk: {data[1]} bytes/sec"; } private void backgroundworker_runworkercompleted(object sender, runworkercompletedeventargs e) { var result = e.result; var cc = e.cancelled; } private void startbutton_click(object sender, eventargs e) { if (backgroundworker.cancellationpending) return; if (isworking) { startbutton.text = "start"; backgroundworker.cancelasync(); } else { startbutton.text = "stop"; backgroundworker.runworkerasync(); } } private void form_closed(object sender, formclosedeventargs e) { if (isworking) { startbutton.enabled = false; backgroundworker.cancelasync(); } } } }
推荐阅读