Share via


Prestatiemeteritems in SqlClient

Van toepassing op: .NET Framework

ADO.NET downloaden

U kunt prestatiemeteritems gebruiken Microsoft.Data.SqlClient om de status van uw toepassing en de verbindingsbronnen te bewaken die worden gebruikt. Prestatiemeteritems kunnen worden bewaakt met Behulp van Windows Performance Monitor of kunnen programmatisch worden geopend met behulp van de PerformanceCounter klasse in de System.Diagnostics naamruimte.

Beschikbare prestatiemeters

Er zijn momenteel 14 verschillende prestatiemeters beschikbaar voor Microsoft.Data.SqlClient, zoals beschreven in de volgende tabel.

Prestatiemeter Description
HardConnectsPerSecond Het aantal verbindingen per seconde dat wordt gemaakt op een databaseserver.
HardDisconnectsPerSecond Het aantal verbroken verbindingen per seconde dat wordt uitgevoerd op een databaseserver.
NumberOfActiveConnectionPoolGroups Het aantal unieke verbindingsgroepgroepen dat actief is. Deze teller wordt bepaald door het aantal unieke verbindingsreeks s die in het AppDomain worden gevonden.
NumberOfActiveConnectionPools Het totale aantal verbindingsgroepen.
NumberOfActiveConnections Het aantal actieve verbindingen dat momenteel wordt gebruikt. Opmerking: deze prestatiemeteritem is niet standaard ingeschakeld. Zie Uitschakelbare tellers activeren om deze prestatiemeter in te schakelen.
NumberOfFreeConnections Het aantal verbindingen dat beschikbaar is voor gebruik in de verbindingsgroepen. Opmerking: deze prestatiemeteritem is niet standaard ingeschakeld. Raadpleeg Niet-standaard tellers activeren om deze prestatiemeter in te schakelen.
NumberOfInactiveConnectionPoolGroups Het aantal unieke verbindingsgroepgroepen dat is gemarkeerd voor het verwijderen. Deze teller wordt bepaald door het aantal unieke verbindingsreeks s die in het AppDomain worden gevonden.
NumberOfInactiveConnectionPools Het aantal inactieve verbindingsgroepen dat geen recente activiteit heeft gehad en die wachten om te worden verwijderd.
NumberOfNonPooledConnections Het aantal actieve verbindingen dat niet is gegroepeerd.
NumberOfPooledConnections Het aantal actieve verbindingen dat wordt beheerd door de infrastructuur voor groepsgewijze verbindingen.
NumberOfReclaimedConnections Het aantal verbindingen dat is vrijgemaakt via garbagecollection waar Close of Dispose niet door de toepassing is aangeroepen. Opmerking Verbindingen niet expliciet sluiten of verwijderen, gaat ten koste van de prestaties.
NumberOfStasisConnections Het aantal verbindingen dat momenteel wacht op voltooiing van een actie en die daarom niet beschikbaar is voor gebruik door uw toepassing.
SoftConnectsPerSecond Het aantal actieve verbindingen dat wordt opgehaald uit de verbindingsgroep. Opmerking: deze prestatiemeteritem is niet standaard ingeschakeld. Zie Standaardtellers activeren om deze prestatiemeter in te schakelen.
SoftDisconnectsPerSecond Het aantal actieve verbindingen dat wordt geretourneerd naar de verbindingsgroep. Opmerking: deze prestatiemeteritem is niet standaard ingeschakeld. Zie Uitsluitend standaard gedeactiveerde tellers activeren om deze prestatieteller in te schakelen.

Tellertjes die standaard zijn uitgeschakeld activeren

De prestatiemeteritemsNumberOfFreeConnections, NumberOfActiveConnectionsen SoftDisconnectsPerSecondSoftConnectsPerSecond zijn standaard uitgeschakeld. Voeg de volgende informatie toe aan het configuratiebestand van de toepassing om ze in te schakelen:

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

Prestatiemeteritemswaarden ophalen

In de volgende consoletoepassing ziet u hoe u prestatiemeteritems ophaalt in uw toepassing. Verbinden moeten open en actief zijn om informatie te retourneren voor alle prestatiemeters van de Microsoft SqlClient Data Provider voor SQL Server.

Opmerking

In dit voorbeeld wordt de voorbeelddatabase AdventureWorks gebruikt. Bij de verbindingsreeksen in de voorbeeldcode wordt ervan uitgegaan dat de database is geïnstalleerd en beschikbaar is op de lokale computer en dat u aanmeldingen hebt gemaakt die overeenkomen met de aanmeldingen die zijn opgegeven in de verbindingsreeksen. Mogelijk moet u SQL Server-aanmeldingen inschakelen als uw server is geconfigureerd met behulp van de standaardbeveiligingsinstellingen die alleen Windows-verificatie toestaan. Pas de verbindingsreeks indien nodig aan uw omgeving aan.

Example

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>;";
        }
    }
}

Zie ook