[.NET] Cannot load Counter Name data because an invalid index หรือ Category does not exist

หลังจากลองเอา Desktop App ที่เป็น Fluent Design ลองใช้งานจริง พอแค่เปิด App เท่านั้นแหละ เจอ Exception เลยครับ 5555


Cannot load Counter Name data because an invalid index

หรือ

Category does not exist


ท้าวความถึงที่มาของปัญหา

Error ตรงนี้มันเกิดมาจากไหนหละ หลังจากลองสีบจาก Code แล้วพบว่า มีการเก็บข้อมูล Performance ของ App นั้นเองครับ โดยมี Code ดังนี้

protected PerformanceCounter _cpuCounter;
protected PerformanceCounter _ramCounter;

//เก็บ Performance Data จาก Process ปัจจุบัน
Process proc = Process.GetCurrentProcess();
_cpuCounter = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName, true);
_ramCounter = new PerformanceCounter("Process", "Private Bytes", proc.ProcessName, true);

ซึ่งข้อมูล Performance มาจากข้อมูลที่ Windows มันเก็บไว้นั้นเองครับ โดย Code ทีดึงข้อมูล สามารถเอามาเก็บข้อมูล หรือ Plot graph ได้ครับ แต่ตรงนี้จะเอามาใส่ตัวแปร String (CurrentPerf) เพื่อนำไปแสดงผลครับ

String CurrentPerf = _cpuCounter.NextValue().ToString("##0.00") + ":" + ((Convert.ToInt64(_ramCounter.NextValue()) / (long)(1024)).ToString("#,##0"));

จาก Code ข้างบนนี่แหละ ตอนเรียก Method NextValue() เจอ Exception "Cannot load Counter Name data because an invalid index" ถ้าลองดูจาก Log จะพบชัดเจนเลยครับ

หลังจากเกริ่นมานานและ ลองมาดูสาเหตุกันครับ

สาเหตุ

  • ตัว counter registry settings หรือ cached performance files มีปัญหาครับ อาจจะเกิดจากเครื่องดับ ทำให้ไฟล์เสียหายครับ

การแก้ไข

  • ซ่อมไฟล์ หรือ Restore จาก backup ที่มีของ OS ครับ โดยใช้คำสั่ง lodctr /r ด้วยสิทธิ admin ครับ ต้องรัน CMD หรือ PowerShell เป็น as administrator ครับ
C:\windows\system32> lodctr /r
  • Note: สำหรับเครื่องที่ Run App 32 bits อาจจะต้องใช้คำสั่งนี้แทนครับ
C:\windows\SysWOW64> lodctr /r
  • ผลลัพธ์ที่ได้
Info: Successfully rebuilt performance counter setting from system backup store

Error อื่นที่พบ

  • Error: Unable to rebuild performance counter setting from system backup store, error code is 5
  • Solution: รัน CMD หรือ PowerShell เป็น as administrator ครับ
  • Error: Unable to rebuild performance counter setting from system backup store, error code is 2
  • Solution: ตรวจสอบว่า App เป็น 32 bits หรือ 64 bits จากนั้น Run คำสั่งอีกรอบครับ

Rerference


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts to your email.