在Asp.Net中使用自定义性能计数器

性能计数器的作用

可以跟踪应用程序的资源使用、运行效率、负载和性能瓶颈等情况。

添加自定义性能计数器

方法一:通过Visual Studio添加性能计数器

打开Visual Studio的“Server Explorer”面板,连接到本地计算机,右键单击 Performance Counters”组,选择“Create New Category”打开添加分类窗口,如下图:

这里可以设置分类名称和描述,新建计数器并设置计数器的类型和描述。点击OK按钮完成后,你可以在“Performance Counters”中查看到你添加的自定义性能计数器,另外可以从注册表中“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”节点查看。

方法二:通过编程方式添加性能计数器。

主要使用System.Diagnostics. PerformanceCounterCategory.Create方法,该方法目前有4个重载版本,如下:

public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, 
    CounterCreationDataCollection counterData);

public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, 
    PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData);

public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, 
    string counterName, string counterHelp);

public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, 
    PerformanceCounterCategoryType categoryType, 
string counterName, string counterHelp);

其中参数categoryType用来指示分类是单实例(single-instance)、多实例(multi-instance)或Unknown类型,默认是单实例,在.Net Framework 1.0/1.1中不需要指定该参数。

具体代码如下:

using System;
using System.Diagnostics;

namespace MyPerformanceCounter
{
    
class Program
    {
        
static void Main(string[] args)
        {
            CreateCounter();

            Console.ReadLine();
        }

        
public static void CreateCounter()
        {
            Console.WriteLine(
"Creating");

            
if (!PerformanceCounterCategory.Exists("MyCategory"))
            {
                PerformanceCounterCategory.Create(
"MyCategory",
                    
"My category description."
                    PerformanceCounterCategoryType.SingleInstance,
                    
"MyCounter",
                    
"This is my first custom performace counter.");
            }
            
else
            {
                Console.WriteLine(
"MyCategory already exists");
            }

            Console.WriteLine(
"Done");
        }
    }
}

在代码中使用性能计数器

这里以使用Increment方法为例,代码如下:

<asp:Button ID="btnIncrement" runat="server" onclick="btnIncrement_Click" Text="增加" />

protected void btnIncrement_Click(object sender, EventArgs e)
{
    PerformanceCounter counter 
= new PerformanceCounter();
    counter.CategoryName 
= "MyCategory";
    counter.CounterName 
= "MyCounter";
    counter.ReadOnly 
= false;

    counter.Increment();
    counter.Close();
}

监视性能计数器

打开管理工具(Administrative Tools)中的性能监视器(Performance Monitor),将自定义的计数器添加到监视器中,点击Web页面中的“增加”按钮,可以看到监视器中计数器的值也跟着增加。

参考链接.NET Framework 中的性能计数器(MSDN

posted on 2008-05-27 19:18  Owen_Zhang  阅读(1110)  评论(1编辑  收藏  举报