SqlClient のパフォーマンス カウンター

適用対象: .NET Framework Not supported. .NET Core Not supported. .NET Standard

ADO.NET のダウンロード

Microsoft.Data.SqlClient のパフォーマンス カウンターを使用して、アプリケーションの状態と使用されている接続リソースを監視できます。 パフォーマンス カウンターは、Windows パフォーマンス モニターを使って監視できるほか、PerformanceCounter 名前空間の System.Diagnostics クラスを使用することでプログラムから監視することもできます。

利用できるパフォーマンス カウンター

次の表に示すように、現在 Microsoft.Data.SqlClient で使用できるパフォーマンス カウンターは 14 個あります。

パフォーマンス カウンター 説明
HardConnectsPerSecond データベース サーバーに対する 1 秒あたりの接続数。
HardDisconnectsPerSecond データベース サーバーに対する 1 秒あたりの切断数。
NumberOfActiveConnectionPoolGroups アクティブな一意の接続プール グループの数。 このカウンターは、AppDomain に見つかった一意の接続文字列数によって制御されます。
NumberOfActiveConnectionPools 接続プールの合計数。
NumberOfActiveConnections 現在使用中のアクティブな接続の数。 注: このパフォーマンス カウンターは、既定では無効にされています。 このパフォーマンス カウンターを有効にするには、「既定でオフになっているカウンターのアクティブ化」を参照してください。
NumberOfFreeConnections 接続プール内の利用可能な接続数。 注: このパフォーマンス カウンターは、既定では無効にされています。 このパフォーマンス カウンターを有効にするには、「既定でオフになっているカウンターのアクティブ化」を参照してください。
NumberOfInactiveConnectionPoolGroups 排除対象としてマークされた一意の接続プール グループの数。 このカウンターは、AppDomain に見つかった一意の接続文字列数によって制御されます。
NumberOfInactiveConnectionPools 最近のアクティビティが存在せず、破棄待ち状態となっている、アクティブでない接続プールの数。
NumberOfNonPooledConnections プールされていないアクティブな接続の数。
NumberOfPooledConnections 接続プール インフラストラクチャによって管理されているアクティブな接続の数。
NumberOfReclaimedConnections アプリケーションによって CloseDispose も呼び出されなかった場合に、ガベージ コレクションによって回収された接続の数。 明示的に終了または破棄しないと、パフォーマンスに悪影響を及ぼします。
NumberOfStasisConnections 現在アクションの完了を待っている (そのためにアプリケーションからは使用できない) 接続の数。
SoftConnectsPerSecond 接続プールからプルされているアクティブな接続の数。 注: このパフォーマンス カウンターは、既定では無効にされています。 このパフォーマンス カウンターを有効にするには、「既定でオフになっているカウンターのアクティブ化」を参照してください。
SoftDisconnectsPerSecond 接続プールに戻されているアクティブな接続の数。 注: このパフォーマンス カウンターは、既定では無効にされています。 このパフォーマンス カウンターを有効にするには、「既定でオフになっているカウンターのアクティブ化」を参照してください。

既定でオフになっているカウンターのアクティブ化

NumberOfFreeConnectionsNumberOfActiveConnectionsSoftDisconnectsPerSecondSoftConnectsPerSecond の各パフォーマンス カウンターは、既定ではオフになっています。 有効にするには、アプリケーションの構成ファイルに次の情報を追加します。

<system.diagnostics>  
  <switches>  
    <add name="ConnectionPoolPerformanceCounterDetail" value="4"/>  
    <!-- A value of 4 corresponds to System.Diagnostics.TraceLevel.Verbose -->
  </switches>  
</system.diagnostics>  

パフォーマンス カウンター値の取得

次のコンソール アプリケーションは、アプリケーションでパフォーマンス カウンターの値を取得する方法を示しています。 情報が返されるには、Microsoft SqlClient Data Provider for SQL Server のすべてのパフォーマンス カウンターについて、接続が開かれておりアクティブである必要があります。

注意

この例では、サンプルの AdventureWorks データベースを使用します。 サンプル コードに示されている接続文字列は、データベースがローカル コンピューターにインストールされており、かつ使用可能であること、および接続文字列で指定されたログインと一致するログインが作成されていることを前提としています。 既定のセキュリティ設定を使用するようにサーバーが構成されている場合、そのままでは Windows 認証しか許可されないため、SQL Server ログインを有効にする必要があります。 接続文字列は環境に合わせて変更してください。

using System;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PerformanceCounterTest
{
    class Program
    {
        PerformanceCounter[] PerfCounters = new PerformanceCounter[10];
        SqlConnection connection = new SqlConnection();

        static void Main()
        {
            Program prog = new Program();
            // Open a connection and create the performance counters.  
            prog.connection.ConnectionString =
               GetIntegratedSecurityConnectionString();
            prog.SetUpPerformanceCounters();
            Console.WriteLine("Available Performance Counters:");

            // Create the connections and display the results.  
            prog.CreateConnections();
            Console.WriteLine("Press Enter to finish.");
            Console.ReadLine();
        }

        private void CreateConnections()
        {
            // List the Performance counters.  
            WritePerformanceCounters();

            // Create 4 connections and display counter information.  
            SqlConnection connection1 = new SqlConnection(
                  GetIntegratedSecurityConnectionString());
            connection1.Open();
            Console.WriteLine("Opened the 1st Connection:");
            WritePerformanceCounters();

            SqlConnection connection2 = new SqlConnection(
                  GetSqlConnectionStringDifferent());
            connection2.Open();
            Console.WriteLine("Opened the 2nd Connection:");
            WritePerformanceCounters();

            SqlConnection connection3 = new SqlConnection(
                  GetSqlConnectionString());
            connection3.Open();
            Console.WriteLine("Opened the 3rd Connection:");
            WritePerformanceCounters();

            SqlConnection connection4 = new SqlConnection(
                  GetSqlConnectionString());
            connection4.Open();
            Console.WriteLine("Opened the 4th Connection:");
            WritePerformanceCounters();

            connection1.Close();
            Console.WriteLine("Closed the 1st Connection:");
            WritePerformanceCounters();

            connection2.Close();
            Console.WriteLine("Closed the 2nd Connection:");
            WritePerformanceCounters();

            connection3.Close();
            Console.WriteLine("Closed the 3rd Connection:");
            WritePerformanceCounters();

            connection4.Close();
            Console.WriteLine("Closed the 4th Connection:");
            WritePerformanceCounters();
        }

        private enum ADO_Net_Performance_Counters
        {
            NumberOfActiveConnectionPools,
            NumberOfReclaimedConnections,
            HardConnectsPerSecond,
            HardDisconnectsPerSecond,
            NumberOfActiveConnectionPoolGroups,
            NumberOfInactiveConnectionPoolGroups,
            NumberOfInactiveConnectionPools,
            NumberOfNonPooledConnections,
            NumberOfPooledConnections,
            NumberOfStasisConnections
            // The following performance counters are more expensive to track.  
            // Enable ConnectionPoolPerformanceCounterDetail in your config file.  
            //     SoftConnectsPerSecond  
            //     SoftDisconnectsPerSecond  
            //     NumberOfActiveConnections  
            //     NumberOfFreeConnections  
        }

        private void SetUpPerformanceCounters()
        {
            connection.Close();
            this.PerfCounters = new PerformanceCounter[10];
            string instanceName = GetInstanceName();
            Type apc = typeof(ADO_Net_Performance_Counters);
            int i = 0;
            foreach (string s in Enum.GetNames(apc))
            {
                this.PerfCounters[i] = new PerformanceCounter();
                this.PerfCounters[i].CategoryName = ".NET Data Provider for SqlServer";
                this.PerfCounters[i].CounterName = s;
                this.PerfCounters[i].InstanceName = instanceName;
                i++;
            }
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int GetCurrentProcessId();

        private string GetInstanceName()
        {
            //This works for Winforms apps.  
            string instanceName =
                System.Reflection.Assembly.GetEntryAssembly().GetName().Name;

            // Must replace special characters like (, ), #, /, \\  
            string instanceName2 =
                AppDomain.CurrentDomain.FriendlyName.ToString().Replace('(', '[')
                .Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_');

            // For ASP.NET applications your instanceName will be your CurrentDomain's
            // FriendlyName. Replace the line above that sets the instanceName with this:  
            // instanceName = AppDomain.CurrentDomain.FriendlyName.ToString().Replace('(','[')  
            // .Replace(')',']').Replace('#','_').Replace('/','_').Replace('\\','_');  

            string pid = GetCurrentProcessId().ToString();
            instanceName = instanceName + "[" + pid + "]";
            Console.WriteLine("Instance Name: {0}", instanceName);
            Console.WriteLine("---------------------------");
            return instanceName;
        }

        private void WritePerformanceCounters()
        {
            Console.WriteLine("---------------------------");
            foreach (PerformanceCounter p in this.PerfCounters)
            {
                Console.WriteLine("{0} = {1}", p.CounterName, p.NextValue());
            }
            Console.WriteLine("---------------------------");
        }

        private static string GetIntegratedSecurityConnectionString()
        {
            // To avoid storing the connection string in your code,  
            // you can retrieve it from a configuration file.  
            return @"Data Source=.;Integrated Security=True;" +
              "Initial Catalog=AdventureWorks";
        }
        private static string GetSqlConnectionString()
        {
            // To avoid storing the connection string in your code,  
            // you can retrieve it from a configuration file.  
            return @"Data Source=.;User Id=<myUserID>;Password=<myPassword>;" +
              "Initial Catalog=AdventureWorks";
        }

        private static string GetSqlConnectionStringDifferent()
        {
            // To avoid storing the connection string in your code,  
            // you can retrieve it from a configuration file.  
            return @"Initial Catalog=AdventureWorks;Data Source=.;" +
              "User Id=<myUserID>;Password=<myPassword>;";
        }
    }
}

関連項目