性能计数器枚举器






4.50/5 (9投票s)
枚举机器上注册的所有性能计数器并将结果保存在 XML 文件中
引言
已经有一些文章介绍了 Windows 性能计数器。尽管如此,我仍然发现它们的潜力被管理员低估,并且许多软件开发人员对它们几乎一无所知。

造成这种情况的主要原因之一是性能计数器数量太多!在普通的最终用户机器上,就有数百个。服务器上的性能计数器数量会垂直增加。
目标
本文的目的是展示一种枚举本地机器上所有已注册性能计数器的方法,并提供将枚举结果保存到 XML 文件中的可能性。一旦保存到 XML 文件中,就可以使用 XSLT 转换结果,并以漂亮的“外观和感觉”报告呈现出来。

其动机是为机器上所有可用的性能计数器制作一种快照。这将帮助开发人员和管理员在需要时根据其描述选择理想的性能计数器。在处理诊断和 Windows 内置的“性能监视器”时,我经常被这些计数器的数量庞大以及缺乏一个全面的性能计数器列表所困扰,而无需在 MMC 对话框中单击数百次。
实现
使用可用的 .NET 诊断类,实现这一目标只需要几分钟的时间。
由于此项目仅枚举性能计数器的**类别**以及属于这些类别的所有性能**计数器**,因此我只需要两个处理性能计数器的可用类。
PerformanceCounterCategory
和 PerformanceCounter
都属于 System.Diagnostics
命名空间,如 MSDN 文档所述,该命名空间主要提供允许您与以下内容交互的类:
- 系统进程
- 事件日志
- 和性能计数器
话虽如此,此工具包括四个步骤:
- 检索工具运行的本地机器的名称
// Retrieve the machine's name. txtMachine.Text = Environment.MachineName;
- 检索机器上可用的性能计数器类别
// Get the Categories of Performance Counters performanceCountersMgr.GetPerformanceCountersCategories(txtMachine.Text.ToString()); PerformanceCounterCategory[] categories = performanceCountersMgr.Categories; for (int i = 0; i < categories.Length; i++) { // Show these at the UI UpdateViewCategories(categories[i]); }
- 对于任何选定的类别,检索可用的计数器
// Collect Counters for the selected Category ListView.SelectedListViewItemCollection sel = listViewCategories.SelectedItems; if(sel != null && sel.Count > 0) { // Show Description of the selected Category PerformanceCounterCategory[] category = performanceCountersMgr.Categories; textBoxCategoryDescription.Text = category[sel[0].Index].CategoryHelp; // Acquire the Counters of the selected Category PerformanceCounter[] counters = performanceCountersMgr.GetPerformanceCounters(category[sel[0].Index]); if (counters != null) { for (int i = 0; i < counters.Length; i++) { PerformanceCounter counter = counters[i]; UpdateViewCounters(counter); } listViewCounters.Items[0].Selected = true; } }
- 将结果保存到所需位置的 XML 文件中
XmlTextWriter xml = new XmlTextWriter(filename, Encoding.UTF8); xml.WriteStartDocument(true); xml.WriteStartElement("Categories");
PerformanceCounterCategory[] category = performanceCountersMgr.Categories;
for (int i = 0; i < category.Length; i++) { xml.WriteStartElement("Categorie"); xml.WriteStartAttribute("Name"); xml.WriteString(category[i].CategoryName);
if (checkBoxCategoryDescription.Checked) { xml.WriteStartAttribute("Description"); xml.WriteString(category[i].CategoryHelp); } xml.WriteEndAttribute(); xml.WriteEndElement(); }
// End of Categories Element xml.WriteEndElement(); xml.Close();
结论
本文展示了如何使用少量可用的 .NET 诊断类枚举本地机器上的性能计数器,以及如何使用 XmlTextWriter
类将枚举序列化到 XML 文件中。在远程机器上枚举这些计数器作为练习留给读者。
历史
- 2010 年 2 月 11 日 - 枚举性能计数器的类别及其关联的计数器