public abstract void AttachPerformanceCountersToMembers
 (
     string categoryName
     , string instanceName
     , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
     , long?initializePerformanceCounterInstanceRawValue = null
 );
Exemplo n.º 2
0
        private static PerformanceCounter CreatePerformanceCounter
        (
            string categoryName
            , string counterName
            , string instanceName
            , PerformanceCounterInstanceLifetime instanceLifetime
            , long?instanceInitializeRawValue
        )
        {
            var performanceCounter = new PerformanceCounter()
            {
                CategoryName = categoryName
                ,
                CounterName = counterName
                ,
                InstanceLifetime = instanceLifetime
                ,
                InstanceName = instanceName
                ,
                ReadOnly = false
                           //                                    ,
                           //RawValue = 0
            };

            if (instanceInitializeRawValue != null)
            {
                performanceCounter.RawValue = instanceInitializeRawValue.Value;
            }
            return(performanceCounter);
        }
 public override void AttachPerformanceCountersToMembers
                         (
                             string categoryName
                             , string instanceName
                             , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
                             , long? initializePerformanceCounterInstanceRawValue = null
                         )
 {
     AttachPerformanceCountersToMembers
             //<CommonPerformanceCountersContainer>
                 (
                     categoryName
                     , instanceName
                     , this
                     , performanceCounterInstanceLifetime
                     , initializePerformanceCounterInstanceRawValue
                 );
     InitializeProcessingTypedPerformanceCounters
             //<CommonPerformanceCountersContainer>
                 (
                     this
                     , PerformanceCounterProcessingFlagsType
                             .IncrementOnBegin
                 );
  
     InitializeProcessingTypedPerformanceCounters
             //<CommonPerformanceCountersContainer>
                 (
                     this
                     , PerformanceCounterProcessingFlagsType
                             .IncrementOnEnd
                 );
     InitializeProcessingTypedPerformanceCounters
             <CommonPerformanceCountersContainer>
                 (
                     this
                     , PerformanceCounterProcessingFlagsType
                             .DecrementOnEnd
                 );
     InitializeProcessingTypedPerformanceCounters
             <CommonPerformanceCountersContainer>
                 (
                     this
                     , PerformanceCounterProcessingFlagsType
                             .TimeBasedOnBeginOnEnd
                 );
     InitializeProcessingTypedPerformanceCountersPairs
             <CommonPerformanceCountersContainer>
                     (
                         this
                         , PerformanceCounterProcessingFlagsType
                                 .TimeBasedOnBeginOnEnd
                     );
 }
        public override void AttachPerformanceCountersToMembers
        (
            string categoryName
            , string instanceName
            , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
            , long?initializePerformanceCounterInstanceRawValue = null
        )
        {
            AttachPerformanceCountersToMembers
            //<CommonPerformanceCountersContainer>
            (
                categoryName
                , instanceName
                , this
                , performanceCounterInstanceLifetime
                , initializePerformanceCounterInstanceRawValue
            );
            InitializeProcessingTypedPerformanceCounters
            //<CommonPerformanceCountersContainer>
            (
                this
                , PerformanceCounterProcessingFlagsType
                .IncrementOnBegin
            );

            InitializeProcessingTypedPerformanceCounters
            //<CommonPerformanceCountersContainer>
            (
                this
                , PerformanceCounterProcessingFlagsType
                .IncrementOnEnd
            );
            InitializeProcessingTypedPerformanceCounters
            <CommonPerformanceCountersContainer>
            (
                this
                , PerformanceCounterProcessingFlagsType
                .DecrementOnEnd
            );
            InitializeProcessingTypedPerformanceCounters
            <CommonPerformanceCountersContainer>
            (
                this
                , PerformanceCounterProcessingFlagsType
                .TimeBasedOnBeginOnEnd
            );
            InitializeProcessingTypedPerformanceCountersPairs
            <CommonPerformanceCountersContainer>
            (
                this
                , PerformanceCounterProcessingFlagsType
                .TimeBasedOnBeginOnEnd
            );
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes the performance counter component
        /// </summary>
        /// <param name="id">Unique identifier for a performance counter</param>
        /// <param name="categoryName">The category of performance counter</param>
        /// <param name="counterName">Name of the performance counter</param>
        /// <param name="instanceName">Performance counter instance</param>
        /// <param name="machineName"> The computer on which the performance counter and its associated                   category exists</param>
        /// <param name="counterLifeTime">Specifies the life time of performance counter instance</param>
        internal Counter(int id, string categoryName, string counterName, string instanceName, string machineName, PerformanceCounterInstanceLifetime counterLifeTime)
        {
            this.performanceCounter = new PerformanceCounter()
            {
                CategoryName = categoryName,
                CounterName = counterName,
                InstanceName = instanceName,
                InstanceLifetime = counterLifeTime,
                MachineName = machineName,
                ReadOnly = false
            };

            this.ID = id;
        }
        public void AttachPerformanceCountersCategoryInstance
        (
            string performanceCountersCategoryName
            , string performanceCountersCategoryInstanceNamePrefix
            , MultiPerformanceCountersTypeFlags enablePerformanceCounters           = MultiPerformanceCountersTypeFlags.ProcessNonTimeBasedCounters
            , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Process
        )
        {
            if (!_isAttachPerformanceCounters)
            {
                _isAttachPerformanceCounters = true;
            }
            else
            {
                CommonPerformanceCountersContainer container = null;
                EasyPerformanceCountersHelper <CommonPerformanceCountersContainer>
                .AttachPerformanceCountersCategoryInstance
                (
                    performanceCountersCategoryName
                    , string.Format
                    (
                        "{1}{0}{2}"
                        , "-"
                        , "Non-Pooled Objects"
                        , performanceCountersCategoryInstanceNamePrefix
                    )
                    , out container
                    , PerformanceCounterInstanceLifetime.Process
                    , initializePerformanceCounterInstanceRawValue : 1009
                );

                EasyPerformanceCountersHelper <CommonPerformanceCountersContainer>
                .AttachPerformanceCountersCategoryInstance
                (
                    performanceCountersCategoryName
                    , string.Format
                    (
                        "{1}{0}{2}"
                        , "-"
                        , "Pooled Objects"
                        , performanceCountersCategoryInstanceNamePrefix
                    )
                    , out container
                    , PerformanceCounterInstanceLifetime.Process
                    , initializePerformanceCounterInstanceRawValue : 1009
                );
            }
        }
 protected void AttachPerformanceCountersToMembers <TContainer>
 (
     string categoryName
     , string instanceName
     , TContainer container
     , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
     , long?initializePerformanceCounterInstanceRawValue = null
 )
 {
     PerformanceCountersHelper
     .AttachPerformanceCountersToMembers <TContainer>
     (
         categoryName
         , instanceName
         , container
         , performanceCounterInstanceLifetime
         , initializePerformanceCounterInstanceRawValue
     );
 }
 /// <summary>
 /// Create a Performance counter install attribute to assist in run-time perfmon counter creation
 /// </summary>
 /// <param name="type">This counters internal type.  Needed base types are automagically created with the name appended with 'base'</param>
 /// <param name="category">This counters category.  All categories are fixed at the time of creation</param>
 /// <param name="lifetime">This counters lifetime, by default all counters are global except for dynamically created instances</param>
 /// <param name="categoryType">The category type (multi or single instance)</param>
 /// <param name="ConnectInstancetype">The CSGO instance type </param>
 /// <param name="counterName">This counters name</param>
 /// <param name="counterHelp">This counters help string</param>
 public PerformanceCounterInstallAttribute(
     PerformanceCounterType type,
     PerformanceCounterCategories category,
     PerformanceCounterInstanceLifetime lifetime,
     PerformanceCounterCategoryType categoryType,
     CounterInstanceType counterInstancetype,
     string counterName,
     string counterHelp,
     string instanceType)
 {
     _type = type;
     _category = category;
     _lifeTime = lifetime;
     _categoryType = categoryType;
     _counterInstanceType = counterInstancetype;
     _counterName = counterName;
     _counterHelp = counterHelp;
     _instanceType = instanceType;
 }
        public static void AttachPerformanceCountersCategoryInstance
        (
            string performanceCountersCategoryName
            , string performanceCountersCategoryInstanceName
            , out TPerformanceCountersContainer container
            , PerformanceCounterInstanceLifetime performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
            , long?initializePerformanceCounterInstanceRawValue = null
        )
        {
            string key = string.Format
                         (
                "{1}{0}{2}"
                , "-"
                , performanceCountersCategoryName
                , performanceCountersCategoryInstanceName
                         );

            //TPerformanceCountersContainer container = null;
            if (!_dictionary.TryGetValue(key, out container))
            {
                lock (_lockerObject)
                {
                    container = new TPerformanceCountersContainer(); //default(TPerformanceCountersContainer);
                    _dictionary
                    .Add
                    (
                        key
                        , container
                    );
                    container
                    .AttachPerformanceCountersToMembers
                    (
                        performanceCountersCategoryName
                        , performanceCountersCategoryInstanceName
                        , performanceCounterInstanceLifetime
                        , initializePerformanceCounterInstanceRawValue
                    );
                }
            }
        }
 internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime)
 {
     this.InitialOffset = 4;
     this.thisInstanceOffset = -1;
     this.categoryName = catName;
     this.categoryNameHashCode = GetWstrHashCode(this.categoryName);
     this.categoryData = this.GetCategoryData();
     if (this.categoryData.UseUniqueSharedMemory)
     {
         if ((instanceName != null) && (instanceName.Length > 0x7f))
         {
             throw new InvalidOperationException(SR.GetString("InstanceNameTooLong"));
         }
     }
     else if (lifetime != PerformanceCounterInstanceLifetime.Global)
     {
         throw new InvalidOperationException(SR.GetString("ProcessLifetimeNotValidInGlobal"));
     }
     if (((counterName != null) && (instanceName != null)) && this.categoryData.CounterNames.Contains(counterName))
     {
         this.counterEntryPointer = this.GetCounter(counterName, instanceName, this.categoryData.EnableReuse, lifetime);
     }
 }
 public override void AttachPerformanceCountersToMembers
 (
     string categoryName
     , string instanceName
     , PerformanceCounterInstanceLifetime
     performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
     , long?initializePerformanceCounterInstanceRawValue = null
 )
 {
     if (!_isAttachedPerformanceCounters)
     {
         //var type = this.GetType();
         AttachPerformanceCountersToMembers <QueuePerformanceCountersContainer>
         (
             categoryName
             , instanceName
             , this
             , performanceCounterInstanceLifetime
             , initializePerformanceCounterInstanceRawValue
         );
     }
     _isAttachedPerformanceCounters = true;
 }
        public void AttachPerformanceCounters
        (
            string categoryName
            , string instanceNamePrefix
            , QueuePerformanceCountersContainer performanceCounters
            , Func <bool> onEnabledCountPerformanceProcessFunc = null
            , PerformanceCounterInstanceLifetime
            performanceCounterInstanceLifetime
            = PerformanceCounterInstanceLifetime.Global
            , long?initializePerformanceCounterInstanceRawValue = null
        )
        {
            var process      = Process.GetCurrentProcess();
            var processName  = process.ProcessName;
            var instanceName = string
                               .Format
                               (
                "{0}-{1}"
                , instanceNamePrefix
                , processName
                               );

            PerformanceCountersContainer = performanceCounters;
            PerformanceCountersContainer
            .AttachPerformanceCountersToMembers
            (
                categoryName
                , instanceName
                , performanceCounterInstanceLifetime
                , initializePerformanceCounterInstanceRawValue
            );
            PerformanceCountersContainer
            .RegisterCountersUsage();
            _isAttachedPerformanceCounters        = true;
            _onEnabledCountPerformanceProcessFunc = onEnabledCountPerformanceProcessFunc;
        }
Exemplo n.º 13
0
        /// <summary>
        /// In this method we instantiate the PerformanceCounter object and return it.
        /// </summary>
        /// <param name="categoryName">Category name</param>
        /// <param name="counterName">Counter name</param>
        /// <param name="instanceName">Counter instance name</param>
        /// <param name="instanceLifeTime">The life time of this instance</param>
        /// <param name="readOnly">Is counter for read only?</param>
        /// <returns>Performance counter</returns>
        public static PerformanceCounter getCounter(
            string categoryName,
            string counterName,
            string instanceName,
            PerformanceCounterInstanceLifetime instanceLifeTime,
            bool readOnly
            )
        {
            PerformanceCounter counter = null;

            // Check if the category exists
            if (PerformanceCounterCategory.Exists(categoryName))
            {
                counter =
                    new PerformanceCounter(
                        categoryName,
                        counterName,
                        instanceName,
                        readOnly
                        );
            }

            return(counter);
        }
Exemplo n.º 14
0
        static internal PerformanceCounter GetPerformanceCounterInternal(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;

            try
            {
                counter = new PerformanceCounter();
                counter.CategoryName     = categoryName;
                counter.CounterName      = perfCounterName;
                counter.InstanceName     = instanceName;
                counter.ReadOnly         = false;
                counter.InstanceLifetime = instanceLifetime;

                // We now need to access the counter raw data to
                // force the counter object to be initialized.  This
                // will force any exceptions due to mis-installation
                // of counters to occur here and be traced appropriately.
                try
                {
                    long rawValue = counter.RawValue;
                }
                catch (InvalidOperationException)
                {
                    counter = null;
                    throw;
                }
                catch (SecurityException securityException)
                {
                    // Cannot access performance counter due to partial trust scenarios
                    // Disable the default performance counters' access otherwise
                    // in PT the service will be broken
                    PerformanceCounters.scope = PerformanceCounterScope.Off;

                    DiagnosticUtility.TraceHandledException(new SecurityException(SR.GetString(
                                                                                      SR.PartialTrustPerformanceCountersNotEnabled), securityException), TraceEventType.Warning);

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new SecurityException(SR.GetString(
                                                        SR.PartialTrustPerformanceCountersNotEnabled)));
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (null != counter)
                {
                    if (!counter.ReadOnly)
                    {
                        try
                        {
                            counter.RemoveInstance();
                        }
                        // Already inside a catch block for a failure case
                        // ok to ---- any exceptions here and trace the
                        // original failure.
#pragma warning suppress 56500 // covered by FxCOP
                        catch (Exception e1)
                        {
                            if (Fx.IsFatal(e1))
                            {
                                throw;
                            }
                        }
                    }

                    counter = null;
                }
                bool logEvent = true;
                if (categoryName == PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters)
                {
                    if (serviceOOM == false)
                    {
                        serviceOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }
                else if (categoryName == PerformanceCounterStrings.SERVICEMODELOPERATION.OperationPerfCounters)
                {
                    if (operationOOM == false)
                    {
                        operationOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }
                else if (categoryName == PerformanceCounterStrings.SERVICEMODELENDPOINT.EndpointPerfCounters)
                {
                    if (endpointOOM == false)
                    {
                        endpointOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }

                if (logEvent)
                {
                    DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                                                        (ushort)System.Runtime.Diagnostics.EventLogCategory.PerformanceCounter,
                                                        (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToLoadPerformanceCounter,
                                                        categoryName,
                                                        perfCounterName,
                                                        e.ToString());
                }
            }
            return(counter);
        }
        static internal PerformanceCounter GetPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;
            if (PerformanceCounters.PerformanceCountersEnabled || PerformanceCounters.MinimalPerformanceCountersEnabled)
            {
                counter = PerformanceCounters.GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime);
            }

            return counter;
        }
Exemplo n.º 16
0
 static PerformanceCounter GetListenerPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
 {
     return(PerformanceCounters.GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime));
 }
        private unsafe static void PopulateLifetimeEntry(ProcessLifetimeEntry *lifetimeEntry, PerformanceCounterInstanceLifetime lifetime) {

            if (lifetime == PerformanceCounterInstanceLifetime.Process) {

                lifetimeEntry->LifetimeType = (int) PerformanceCounterInstanceLifetime.Process;
                lifetimeEntry->ProcessId = ProcessData.ProcessId;
                lifetimeEntry->StartupTime = ProcessData.StartupTime;
            }
            else {
                lifetimeEntry->ProcessId = 0;
                lifetimeEntry->StartupTime = 0;
            }
        }
        private unsafe bool FindInstance(int instanceNameHashCode, string instanceName, 
                                           CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference, 
                                           bool activateUnusedInstances, PerformanceCounterInstanceLifetime lifetime, 
                                           out bool foundFreeInstance) {

            InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
            InstanceEntry* previousInstancePointer = currentInstancePointer;
            foundFreeInstance = false;
            // Look at the first instance to determine if this is single or multi instance. 
            if (currentInstancePointer->InstanceNameHashCode == SingleInstanceHashCode) {
                if (StringEquals(SingleInstanceName, currentInstancePointer->InstanceNameOffset)){
                    if (instanceName != SingleInstanceName)
                        throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, categoryName));
                }
                else {
                    if (instanceName == SingleInstanceName)
                        throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, categoryName));
                }
            }
            else {
                if (instanceName == SingleInstanceName)
                    throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, categoryName));
            }

            //
            // 1st pass find exact matching!
            // 
            // We don't need to aggressively claim unused instances. For performance, we would proactively 
            // verify lifetime of instances if activateUnusedInstances is specified and certain time 
            // has elapsed since last sweep or we are running out of shared memory.  
            bool verifyLifeTime = activateUnusedInstances;
            if (activateUnusedInstances) {
                
                int totalSize = InstanceEntrySize + ProcessLifetimeEntrySize + InstanceNameSlotSize +  (CounterEntrySize * categoryData.CounterNames.Count);
                int freeMemoryOffset = *((int *) baseAddress);
                int alignmentAdjustment;
                int newOffset = CalculateMemoryNoBoundsCheck(freeMemoryOffset, totalSize, out alignmentAdjustment);

                if (!(newOffset > FileView.FileMappingSize || newOffset < 0)) {
                    long tickDelta = (DateTime.Now.Ticks - Volatile.Read(ref LastInstanceLifetimeSweepTick));  
                    if (tickDelta < InstanceLifetimeSweepWindow) 
                        verifyLifeTime = false;    
                }
            }

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
            try {
                for(;;) {
                    bool verifiedLifetimeOfThisInstance = false;
                    if (verifyLifeTime && (currentInstancePointer->RefCount != 0)) {
                        verifiedLifetimeOfThisInstance = true;
                        VerifyLifetime(currentInstancePointer);
                    }
                    
                    if (currentInstancePointer->InstanceNameHashCode == instanceNameHashCode) {
                        if (StringEquals(instanceName, currentInstancePointer->InstanceNameOffset)){
                            // we found a matching instance. 
                            *returnInstancePointerReference = currentInstancePointer;
    
                            CounterEntry* firstCounter = (CounterEntry*) ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
                            ProcessLifetimeEntry* lifetimeEntry;
                            if (categoryData.UseUniqueSharedMemory) 
                                lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(firstCounter->LifetimeOffset, ProcessLifetimeEntrySize);
                            else
                                lifetimeEntry = null;
                            
                            // ensure that we have verified the lifetime of the matched instance
                            if (!verifiedLifetimeOfThisInstance && currentInstancePointer->RefCount != 0) 
                                VerifyLifetime(currentInstancePointer);
                                
                            if (currentInstancePointer->RefCount != 0) {
                                if (lifetimeEntry != null && lifetimeEntry->ProcessId != 0) {
                                    if (lifetime != PerformanceCounterInstanceLifetime.Process)
                                        throw new InvalidOperationException(SR.GetString(SR.CantConvertProcessToGlobal));
                                        
                                    // make sure only one process is using this instance. 
                                    if (ProcessData.ProcessId != lifetimeEntry->ProcessId)
                                        throw new InvalidOperationException(SR.GetString(SR.InstanceAlreadyExists, instanceName));

                                   // compare start time of the process, account for ACL issues in querying process information
                                    if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1)) { 
                                        if (ProcessData.StartupTime != lifetimeEntry->StartupTime)
                                            throw new InvalidOperationException(SR.GetString(SR.InstanceAlreadyExists, instanceName));
                                    }
                                }
                                else {
                                    if (lifetime == PerformanceCounterInstanceLifetime.Process)
                                        throw new InvalidOperationException(SR.GetString(SR.CantConvertGlobalToProcess));
                                }
                                return true;
                            }
                            
                            if (activateUnusedInstances) {
                                Mutex mutex = null;
                                RuntimeHelpers.PrepareConstrainedRegions();
                                try {
                                    SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
                                    ClearCounterValues(currentInstancePointer);
                                    if (lifetimeEntry != null)
                                        PopulateLifetimeEntry(lifetimeEntry, lifetime);
                                    
                                    currentInstancePointer->RefCount = 1;
                                    return true;
                                }
                                finally {
                                    if (mutex != null) {
                                        mutex.ReleaseMutex();
                                        mutex.Close();
                                    }
                                }
                            }
                            else
                                return false;
                        }
                    }
    
                    if (currentInstancePointer->RefCount == 0) {
                        foundFreeInstance = true;
                    }
    
                    previousInstancePointer = currentInstancePointer;
                    if (currentInstancePointer->NextInstanceOffset != 0)
                        currentInstancePointer =  (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize));
                    else {
                        *returnInstancePointerReference = previousInstancePointer;
                        return false;
                    }
                }
            }
            finally  {
                SecurityPermission.RevertAssert();
                
                if (verifyLifeTime) 
                    Volatile.Write(ref LastInstanceLifetimeSweepTick, DateTime.Now.Ticks);
            }
        }
 private unsafe CounterEntry* GetCounter(string counterName, string instanceName, bool enableReuse, PerformanceCounterInstanceLifetime lifetime)
 {
     int singleInstanceHashCode;
     CounterEntry* entryPtr5;
     int wstrHashCode = GetWstrHashCode(counterName);
     if ((instanceName != null) && (instanceName.Length != 0))
     {
         singleInstanceHashCode = GetWstrHashCode(instanceName);
     }
     else
     {
         singleInstanceHashCode = SingleInstanceHashCode;
         instanceName = "systemdiagnosticssharedsingleinstance";
     }
     Mutex mutex = null;
     CounterEntry* returnCounterPointerReference = null;
     InstanceEntry* instancePointer = null;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         CategoryEntry* entryPtr3;
         bool flag2;
         bool flag5;
         SharedUtils.EnterMutexWithoutGlobal(this.categoryData.MutexName, ref mutex);
         while (!this.FindCategory(&entryPtr3))
         {
             bool flag;
             if (this.categoryData.UseUniqueSharedMemory)
             {
                 flag = true;
             }
             else
             {
                 WaitAndEnterCriticalSection(&entryPtr3->SpinLock, out flag);
             }
             if (flag)
             {
                 int num3;
                 try
                 {
                     num3 = this.CreateCategory(entryPtr3, singleInstanceHashCode, instanceName, lifetime);
                 }
                 finally
                 {
                     if (!this.categoryData.UseUniqueSharedMemory)
                     {
                         ExitCriticalSection(&entryPtr3->SpinLock);
                     }
                 }
                 entryPtr3 = (CategoryEntry*) this.ResolveOffset(num3, CategoryEntrySize);
                 instancePointer = (InstanceEntry*) this.ResolveOffset(entryPtr3->FirstInstanceOffset, InstanceEntrySize);
                 this.FindCounter(wstrHashCode, counterName, instancePointer, &returnCounterPointerReference);
                 return returnCounterPointerReference;
             }
         }
         while (!this.FindInstance(singleInstanceHashCode, instanceName, entryPtr3, &instancePointer, true, lifetime, out flag2))
         {
             bool flag3;
             InstanceEntry* lockInstancePointer = instancePointer;
             if (this.categoryData.UseUniqueSharedMemory)
             {
                 flag3 = true;
             }
             else
             {
                 WaitAndEnterCriticalSection(&lockInstancePointer->SpinLock, out flag3);
             }
             if (flag3)
             {
                 try
                 {
                     bool flag4 = false;
                     if (enableReuse && flag2)
                     {
                         flag4 = this.TryReuseInstance(singleInstanceHashCode, instanceName, entryPtr3, &instancePointer, lifetime, lockInstancePointer);
                     }
                     if (!flag4)
                     {
                         int offset = this.CreateInstance(entryPtr3, singleInstanceHashCode, instanceName, lifetime);
                         instancePointer = (InstanceEntry*) this.ResolveOffset(offset, InstanceEntrySize);
                         this.FindCounter(wstrHashCode, counterName, instancePointer, &returnCounterPointerReference);
                         return returnCounterPointerReference;
                     }
                     continue;
                 }
                 finally
                 {
                     if (!this.categoryData.UseUniqueSharedMemory)
                     {
                         ExitCriticalSection(&lockInstancePointer->SpinLock);
                     }
                 }
             }
         }
         if (!this.categoryData.UseUniqueSharedMemory)
         {
             goto Label_01FC;
         }
         this.FindCounter(wstrHashCode, counterName, instancePointer, &returnCounterPointerReference);
         return returnCounterPointerReference;
     Label_01C0:
         WaitAndEnterCriticalSection(&returnCounterPointerReference->SpinLock, out flag5);
         if (flag5)
         {
             try
             {
                 int num5 = this.CreateCounter(returnCounterPointerReference, wstrHashCode, counterName);
                 return (CounterEntry*) this.ResolveOffset(num5, CounterEntrySize);
             }
             finally
             {
                 ExitCriticalSection(&returnCounterPointerReference->SpinLock);
             }
         }
     Label_01FC:
         if (!this.FindCounter(wstrHashCode, counterName, instancePointer, &returnCounterPointerReference))
         {
             goto Label_01C0;
         }
         entryPtr5 = returnCounterPointerReference;
     }
     finally
     {
         try
         {
             if ((returnCounterPointerReference != null) && (instancePointer != null))
             {
                 this.thisInstanceOffset = this.ResolveAddress((long) ((ulong) instancePointer), InstanceEntrySize);
             }
         }
         catch (InvalidOperationException)
         {
             this.thisInstanceOffset = -1;
         }
         if (mutex != null)
         {
             mutex.ReleaseMutex();
             mutex.Close();
         }
     }
     return entryPtr5;
 }
        private unsafe int CreateCategory(CategoryEntry* lastCategoryPointer, 
                                            int instanceNameHashCode, string instanceName, 
                                            PerformanceCounterInstanceLifetime lifetime) {
            int categoryNameLength;
            int instanceNameLength;
            int alignmentAdjustment;
            int freeMemoryOffset;
            int newOffset = 0;
            int totalSize;

            categoryNameLength = (categoryName.Length + 1) * 2;
            totalSize = CategoryEntrySize + InstanceEntrySize + (CounterEntrySize * categoryData.CounterNames.Count) + categoryNameLength;
            for (int i=0; i<categoryData.CounterNames.Count; i++) {
                totalSize += (((string)categoryData.CounterNames[i]).Length + 1) * 2;
            }

            if (categoryData.UseUniqueSharedMemory) {
                instanceNameLength = InstanceNameSlotSize;
                totalSize += ProcessLifetimeEntrySize + instanceNameLength;

                // If we're in a separate shared memory, we need to do a two stage update of the free memory pointer.
                // First we calculate our alignment adjustment and where the new free offset is.  Then we 
                // write the new structs and data.  The last two operations are to link the new structs into the 
                // existing ones and update the next free offset.  Our process could get killed in between those two,
                // leaving the memory in an inconsistent state.  We use the "IsConsistent" flag to help determine 
                // when that has happened. 
                freeMemoryOffset = *((int *) baseAddress);
                newOffset = CalculateMemory(freeMemoryOffset, totalSize, out alignmentAdjustment);

                if (freeMemoryOffset == InitialOffset)
                    lastCategoryPointer->IsConsistent = 0;
            }
            else {
                instanceNameLength = (instanceName.Length +1) * 2;
                totalSize += instanceNameLength;
                freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
            }

            long nextPtr = ResolveOffset(freeMemoryOffset, totalSize + alignmentAdjustment);
            
            CategoryEntry* newCategoryEntryPointer;
            InstanceEntry* newInstanceEntryPointer;
            // We need to decide where to put the padding returned in alignmentAdjustment.  There are several things that
            // need to be aligned.  First, we need to align each struct on a 4 byte boundary so we can use interlocked 
            // operations on the int Spinlock field.  Second, we need to align the CounterEntry on an 8 byte boundary so that
            // on 64 bit platforms we can use interlocked operations on the Value field.  alignmentAdjustment guarantees 8 byte
            // alignemnt, so we use that for both.  If we're creating the very first category, however, we can't move that 
            // CategoryEntry.  In this case we put the alignmentAdjustment before the InstanceEntry. 
            if (freeMemoryOffset == InitialOffset) {
                newCategoryEntryPointer = (CategoryEntry*) nextPtr;
                nextPtr += CategoryEntrySize + alignmentAdjustment;
                newInstanceEntryPointer = (InstanceEntry*) nextPtr;
            }
            else {
                nextPtr += alignmentAdjustment;
                newCategoryEntryPointer = (CategoryEntry*) nextPtr;
                nextPtr += CategoryEntrySize;
                newInstanceEntryPointer = (InstanceEntry*) nextPtr;
            }
            nextPtr += InstanceEntrySize;

            // create the first CounterEntry and reserve space for all of the rest.  We won't 
            // finish creating them until the end
            CounterEntry* newCounterEntryPointer = (CounterEntry*) nextPtr;
            nextPtr += CounterEntrySize * categoryData.CounterNames.Count;

            if (categoryData.UseUniqueSharedMemory) {
                ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*) nextPtr;
                nextPtr += ProcessLifetimeEntrySize;
                
                newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - baseAddress);
                PopulateLifetimeEntry(newLifetimeEntry, lifetime);
            }

            newCategoryEntryPointer->CategoryNameHashCode = categoryNameHashCode;
            newCategoryEntryPointer->NextCategoryOffset = 0;
            newCategoryEntryPointer->FirstInstanceOffset = (int)((long)newInstanceEntryPointer - baseAddress);
            newCategoryEntryPointer->CategoryNameOffset = (int) (nextPtr - baseAddress);
            SafeMarshalCopy(categoryName, (IntPtr)nextPtr);
            nextPtr += categoryNameLength;

            newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
            newInstanceEntryPointer->NextInstanceOffset = 0;
            newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
            newInstanceEntryPointer->RefCount = 1;
            newInstanceEntryPointer->InstanceNameOffset = (int) (nextPtr - baseAddress);
            SafeMarshalCopy(instanceName, (IntPtr)nextPtr);
            nextPtr += instanceNameLength;

            string counterName = (string) categoryData.CounterNames[0];
            newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
            SetValue(newCounterEntryPointer, 0);
            newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
            SafeMarshalCopy(counterName, (IntPtr)nextPtr);
            nextPtr += (counterName.Length + 1) * 2;
                
            CounterEntry* previousCounterEntryPointer;
            for (int i=1; i<categoryData.CounterNames.Count; i++) {
                previousCounterEntryPointer = newCounterEntryPointer;
                counterName = (string) categoryData.CounterNames[i];
                
                newCounterEntryPointer++;
                newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
                SetValue(newCounterEntryPointer, 0);
                newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
                SafeMarshalCopy(counterName, (IntPtr)nextPtr);

                nextPtr += (counterName.Length + 1) * 2;
                previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
            }
            
            Debug.Assert(nextPtr - baseAddress == freeMemoryOffset + totalSize + alignmentAdjustment, "We should have used all of the space we requested at this point");
            
            int offset = (int) ((long) newCategoryEntryPointer - baseAddress);
            lastCategoryPointer->IsConsistent = 0;
            // If not the first category node, link it.
            if (offset != InitialOffset)
                lastCategoryPointer->NextCategoryOffset = offset;

            if (categoryData.UseUniqueSharedMemory) {
                *((int*) baseAddress) = newOffset;
                lastCategoryPointer->IsConsistent = 1;
            }
            return offset;
        }
 private unsafe bool FindInstance(int instanceNameHashCode, string instanceName, CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference, bool activateUnusedInstances, PerformanceCounterInstanceLifetime lifetime, out bool foundFreeInstance)
 {
     bool flag3;
     InstanceEntry* currentInstancePointer = (InstanceEntry*) this.ResolveOffset(categoryPointer.FirstInstanceOffset, InstanceEntrySize);
     InstanceEntry* entryPtr2 = currentInstancePointer;
     foundFreeInstance = false;
     if (currentInstancePointer->InstanceNameHashCode == SingleInstanceHashCode)
     {
         if (!this.StringEquals("systemdiagnosticssharedsingleinstance", currentInstancePointer->InstanceNameOffset))
         {
             if (instanceName == "systemdiagnosticssharedsingleinstance")
             {
                 throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { this.categoryName }));
             }
         }
         else if (instanceName != "systemdiagnosticssharedsingleinstance")
         {
             throw new InvalidOperationException(SR.GetString("SingleInstanceOnly", new object[] { this.categoryName }));
         }
     }
     else if (instanceName == "systemdiagnosticssharedsingleinstance")
     {
         throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { this.categoryName }));
     }
     bool flag = activateUnusedInstances;
     if (activateUnusedInstances)
     {
         int num3;
         int totalSize = ((InstanceEntrySize + ProcessLifetimeEntrySize) + 0x100) + (CounterEntrySize * this.categoryData.CounterNames.Count);
         int oldOffset = *((int*) this.baseAddress);
         int num4 = this.CalculateMemoryNoBoundsCheck(oldOffset, totalSize, out num3);
         if ((num4 <= this.FileView.FileMappingSize) && (num4 >= 0))
         {
             long num5 = DateTime.Now.Ticks - LastInstanceLifetimeSweepTick;
             if (num5 < InstanceLifetimeSweepWindow)
             {
                 flag = false;
             }
         }
     }
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
     try
     {
         bool flag2;
     Label_0156:
         flag2 = false;
         if (flag && (currentInstancePointer->RefCount != 0))
         {
             flag2 = true;
             this.VerifyLifetime(currentInstancePointer);
         }
         if ((currentInstancePointer->InstanceNameHashCode == instanceNameHashCode) && this.StringEquals(instanceName, currentInstancePointer->InstanceNameOffset))
         {
             ProcessLifetimeEntry* entryPtr4;
             *((IntPtr*) returnInstancePointerReference) = currentInstancePointer;
             CounterEntry* entryPtr3 = (CounterEntry*) this.ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
             if (this.categoryData.UseUniqueSharedMemory)
             {
                 entryPtr4 = (ProcessLifetimeEntry*) this.ResolveOffset(entryPtr3->LifetimeOffset, ProcessLifetimeEntrySize);
             }
             else
             {
                 entryPtr4 = null;
             }
             if (!flag2 && (currentInstancePointer->RefCount != 0))
             {
                 this.VerifyLifetime(currentInstancePointer);
             }
             if (currentInstancePointer->RefCount != 0)
             {
                 if ((entryPtr4 != null) && (entryPtr4->ProcessId != 0))
                 {
                     if (lifetime != PerformanceCounterInstanceLifetime.Process)
                     {
                         throw new InvalidOperationException(SR.GetString("CantConvertProcessToGlobal"));
                     }
                     if (ProcessData.ProcessId != entryPtr4->ProcessId)
                     {
                         throw new InvalidOperationException(SR.GetString("InstanceAlreadyExists", new object[] { instanceName }));
                     }
                     if (((entryPtr4->StartupTime != -1L) && (ProcessData.StartupTime != -1L)) && (ProcessData.StartupTime != entryPtr4->StartupTime))
                     {
                         throw new InvalidOperationException(SR.GetString("InstanceAlreadyExists", new object[] { instanceName }));
                     }
                 }
                 else if (lifetime == PerformanceCounterInstanceLifetime.Process)
                 {
                     throw new InvalidOperationException(SR.GetString("CantConvertGlobalToProcess"));
                 }
                 return true;
             }
             if (activateUnusedInstances)
             {
                 Mutex mutex = null;
                 RuntimeHelpers.PrepareConstrainedRegions();
                 try
                 {
                     SharedUtils.EnterMutexWithoutGlobal(this.categoryData.MutexName, ref mutex);
                     this.ClearCounterValues(currentInstancePointer);
                     if (entryPtr4 != null)
                     {
                         PopulateLifetimeEntry(entryPtr4, lifetime);
                     }
                     currentInstancePointer->RefCount = 1;
                     return true;
                 }
                 finally
                 {
                     if (mutex != null)
                     {
                         mutex.ReleaseMutex();
                         mutex.Close();
                     }
                 }
             }
             return false;
         }
         if (currentInstancePointer->RefCount == 0)
         {
             foundFreeInstance = true;
         }
         entryPtr2 = currentInstancePointer;
         if (currentInstancePointer->NextInstanceOffset != 0)
         {
             currentInstancePointer = (InstanceEntry*) this.ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize);
             goto Label_0156;
         }
         *((IntPtr*) returnInstancePointerReference) = entryPtr2;
         flag3 = false;
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
         if (flag)
         {
             LastInstanceLifetimeSweepTick = DateTime.Now.Ticks;
         }
     }
     return flag3;
 }
Exemplo n.º 22
0
        public static void AttachPerformanceCountersToMembers <T>
        (
            string categoryName
            , string instanceName
            , T target                            //= default(T)
            , PerformanceCounterInstanceLifetime
            instanceLifetime
            = PerformanceCounterInstanceLifetime.Global
            , long?instanceInitializeRawValue = null
        )
        {
            var type    = typeof(T);
            var members = type
                          .GetMembersByMemberType <PerformanceCounter>()
                          .Concat
                          (
                type
                .GetMembersByMemberType <PerformanceCountersPair>()
                          );

            //.GetProperties()
            //.Where
            //    (
            //        (pi) =>
            //        {
            //            var parameters = pi.GetIndexParameters();
            //            return
            //                (
            //                    (
            //                        pi.PropertyType == typeof(PerformanceCounter)
            //                        ||
            //                        pi.PropertyType == typeof(PerformanceCountersPair)
            //                    )
            //                    && (parameters == null ? 0 : parameters.Length) <= 0
            //                );
            //        }
            //    );
            if (!PerformanceCounterCategory.Exists(categoryName))
            {
                var ccdc = new CounterCreationDataCollection();
                foreach (var memberInfo in members)
                {
                    var memberName             = memberInfo.Name;
                    var performanceCounterType = PerformanceCounterType
                                                 .NumberOfItems64;
                    var performanceCounterName = memberName;
                    var attribute
                        = memberInfo
                          .GetCustomAttribute
                          <PerformanceCounterDefinitionAttribute>
                              ();
                    if (attribute != null)
                    {
                        var counterName = attribute.CounterName;
                        if (!string.IsNullOrEmpty(counterName))
                        {
                            performanceCounterName = counterName;
                        }
                        var counterType = attribute.CounterType;
                        //if (counterType != null)
                        {
                            performanceCounterType = counterType;
                        }
                    }
                    var ccd = GetCounterCreationData
                              (
                        performanceCounterName
                        , performanceCounterType
                              );
                    ccdc.Add(ccd);
                    Type memberType = null;
                    if (memberInfo is FieldInfo)
                    {
                        var fieldInfo = memberInfo as FieldInfo;
                        memberType = fieldInfo.FieldType;
                    }
                    else if (memberInfo is PropertyInfo)
                    {
                        var propertyInfo = memberInfo as PropertyInfo;
                        memberType = propertyInfo.PropertyType;
                    }


                    if (memberType == typeof(PerformanceCountersPair))
                    {
                        performanceCounterName = string.Format("{0}.(Base)", performanceCounterName);
                        var counterName = attribute.BaseCounterName;
                        if (!string.IsNullOrEmpty(counterName))
                        {
                            performanceCounterName = counterName;
                        }
                        var counterType = attribute.BaseCounterType;
                        //if (counterType != null)
                        {
                            performanceCounterType = counterType;
                        }
                        ccd = GetCounterCreationData
                              (
                            performanceCounterName
                            , performanceCounterType
                              );
                        ccdc.Add(ccd);
                    }
                }
                PerformanceCounterCategory
                .Create
                (
                    categoryName
                    , string
                    .Format
                    (
                        "{0} Category Help."
                        , categoryName
                    )
                    , PerformanceCounterCategoryType
                    .MultiInstance
                    , ccdc
                );
            }
            foreach (var memberInfo in members)
            {
                //PerformanceCounter performanceCounter = null;
                var memberName             = memberInfo.Name;
                var performanceCounterType = PerformanceCounterType
                                             .NumberOfItems64;
                var performanceCounterName = memberName;
                //var performanceCounterInstanceLifetime = defaultPerformanceCounterInstanceLifetime;
                long?performanceCounterInstanceInitializeRawValue
                    = instanceInitializeRawValue;
                var attribute
                    = memberInfo
                      .GetCustomAttribute
                      <PerformanceCounterDefinitionAttribute>
                          ();
                if (attribute != null)
                {
                    var counterName = attribute.CounterName;
                    if (!string.IsNullOrEmpty(counterName))
                    {
                        performanceCounterName = counterName;
                    }
                    var counterType = attribute.CounterType;
                    //if (counterType != null)
                    {
                        performanceCounterType = counterType;
                    }
                    var counterInstanceLifetime
                        = attribute.CounterInstanceLifetime;
                    if
                    (
                        counterInstanceLifetime != null
                        &&
                        counterInstanceLifetime.HasValue
                    )
                    {
                        instanceLifetime = counterInstanceLifetime.Value;
                    }
                    var counterInstanceInitializeRawValue
                        = attribute.CounterInstanceInitializeRawValue;
                    if
                    (
                        counterInstanceInitializeRawValue != null
                        &&
                        counterInstanceInitializeRawValue.HasValue
                    )
                    {
                        performanceCounterInstanceInitializeRawValue
                            = counterInstanceInitializeRawValue.Value;
                    }
                }
                var performanceCounter
                    = CreatePerformanceCounter
                      (
                          categoryName
                          , performanceCounterName
                          , instanceName
                          , instanceLifetime
                          , performanceCounterInstanceInitializeRawValue
                      );
                Type memberType = null;
                if (memberInfo is FieldInfo)
                {
                    var fieldInfo = memberInfo as FieldInfo;
                    memberType = fieldInfo.FieldType;
                }
                else if (memberInfo is PropertyInfo)
                {
                    var propertyInfo = memberInfo as PropertyInfo;
                    memberType = propertyInfo.PropertyType;
                }
                if (memberType == typeof(PerformanceCounter))
                {
                    SetMemberValueToTarget(target, memberInfo, performanceCounter);
                }
                else if (memberType == typeof(PerformanceCountersPair))
                {
                    performanceCounterName = string.Format("{0}.(Base)", performanceCounterName);
                    var baseCounterName = attribute.BaseCounterName;
                    if (!string.IsNullOrEmpty(baseCounterName))
                    {
                        performanceCounterName = baseCounterName;
                    }
                    var baseCounterType = attribute.BaseCounterType;
                    {
                        performanceCounterType = baseCounterType;
                    }
                    var basePerformanceCounter
                        = CreatePerformanceCounter
                          (
                              categoryName
                              , performanceCounterName
                              , instanceName
                              , instanceLifetime
                              , performanceCounterInstanceInitializeRawValue
                          );
                    var performanceCountersPair = new PerformanceCountersPair()
                    {
                        Counter       = performanceCounter
                        , BaseCounter = basePerformanceCounter
                    };
                    SetMemberValueToTarget
                    (
                        target
                        , memberInfo
                        , performanceCountersPair
                    );
                }
            }
        }
 private unsafe int CreateInstance(CategoryEntry* categoryPointer, int instanceNameHashCode, string instanceName, PerformanceCounterInstanceLifetime lifetime)
 {
     int num;
     int num3;
     int num4;
     int totalSize = InstanceEntrySize + (CounterEntrySize * this.categoryData.CounterNames.Count);
     int num5 = 0;
     if (this.categoryData.UseUniqueSharedMemory)
     {
         num = 0x100;
         totalSize += ProcessLifetimeEntrySize + num;
         num4 = *((int*) this.baseAddress);
         num5 = this.CalculateMemory(num4, totalSize, out num3);
     }
     else
     {
         num = (instanceName.Length + 1) * 2;
         totalSize += num;
         for (int i = 0; i < this.categoryData.CounterNames.Count; i++)
         {
             totalSize += (((string) this.categoryData.CounterNames[i]).Length + 1) * 2;
         }
         num4 = this.CalculateAndAllocateMemory(totalSize, out num3);
     }
     num4 += num3;
     long num7 = this.ResolveOffset(num4, totalSize);
     InstanceEntry* entryPtr = (InstanceEntry*) num7;
     num7 += InstanceEntrySize;
     CounterEntry* counterEntry = (CounterEntry*) num7;
     num7 += CounterEntrySize * this.categoryData.CounterNames.Count;
     if (this.categoryData.UseUniqueSharedMemory)
     {
         ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*) num7;
         num7 += ProcessLifetimeEntrySize;
         counterEntry->LifetimeOffset = (int) (((ulong) lifetimeEntry) - this.baseAddress);
         PopulateLifetimeEntry(lifetimeEntry, lifetime);
     }
     entryPtr->InstanceNameHashCode = instanceNameHashCode;
     entryPtr->NextInstanceOffset = 0;
     entryPtr->FirstCounterOffset = (int) (((ulong) counterEntry) - this.baseAddress);
     entryPtr->RefCount = 1;
     entryPtr->InstanceNameOffset = (int) (num7 - this.baseAddress);
     SafeMarshalCopy(instanceName, (IntPtr) num7);
     num7 += num;
     if (this.categoryData.UseUniqueSharedMemory)
     {
         InstanceEntry* entryPtr4 = (InstanceEntry*) this.ResolveOffset(categoryPointer.FirstInstanceOffset, InstanceEntrySize);
         CounterEntry* entryPtr5 = (CounterEntry*) this.ResolveOffset(entryPtr4->FirstCounterOffset, CounterEntrySize);
         counterEntry->CounterNameHashCode = entryPtr5->CounterNameHashCode;
         SetValue(counterEntry, 0L);
         counterEntry->CounterNameOffset = entryPtr5->CounterNameOffset;
         for (int j = 1; j < this.categoryData.CounterNames.Count; j++)
         {
             CounterEntry* entryPtr6 = counterEntry;
             counterEntry++;
             entryPtr5 = (CounterEntry*) this.ResolveOffset(entryPtr5->NextCounterOffset, CounterEntrySize);
             counterEntry->CounterNameHashCode = entryPtr5->CounterNameHashCode;
             SetValue(counterEntry, 0L);
             counterEntry->CounterNameOffset = entryPtr5->CounterNameOffset;
             entryPtr6->NextCounterOffset = (int) (((ulong) counterEntry) - this.baseAddress);
         }
     }
     else
     {
         CounterEntry* entryPtr7 = null;
         for (int k = 0; k < this.categoryData.CounterNames.Count; k++)
         {
             string wstr = (string) this.categoryData.CounterNames[k];
             counterEntry->CounterNameHashCode = GetWstrHashCode(wstr);
             counterEntry->CounterNameOffset = (int) (num7 - this.baseAddress);
             SafeMarshalCopy(wstr, (IntPtr) num7);
             num7 += (wstr.Length + 1) * 2;
             SetValue(counterEntry, 0L);
             if (k != 0)
             {
                 entryPtr7->NextCounterOffset = (int) (((ulong) counterEntry) - this.baseAddress);
             }
             entryPtr7 = counterEntry;
             counterEntry++;
         }
     }
     int num10 = (int) (((ulong) entryPtr) - this.baseAddress);
     categoryPointer.IsConsistent = 0;
     entryPtr->NextInstanceOffset = categoryPointer.FirstInstanceOffset;
     categoryPointer.FirstInstanceOffset = num10;
     if (this.categoryData.UseUniqueSharedMemory)
     {
         this.baseAddress[0] = num5;
         categoryPointer.IsConsistent = 1;
     }
     return num4;
 }
 private unsafe int CreateCategory(CategoryEntry* lastCategoryPointer, int instanceNameHashCode, string instanceName, PerformanceCounterInstanceLifetime lifetime)
 {
     int num2;
     int num3;
     int num4;
     CategoryEntry* entryPtr;
     InstanceEntry* entryPtr2;
     int num5 = 0;
     int num = (this.categoryName.Length + 1) * 2;
     int totalSize = ((CategoryEntrySize + InstanceEntrySize) + (CounterEntrySize * this.categoryData.CounterNames.Count)) + num;
     for (int i = 0; i < this.categoryData.CounterNames.Count; i++)
     {
         totalSize += (((string) this.categoryData.CounterNames[i]).Length + 1) * 2;
     }
     if (this.categoryData.UseUniqueSharedMemory)
     {
         num2 = 0x100;
         totalSize += ProcessLifetimeEntrySize + num2;
         num4 = *((int*) this.baseAddress);
         num5 = this.CalculateMemory(num4, totalSize, out num3);
         if (num4 == this.InitialOffset)
         {
             lastCategoryPointer.IsConsistent = 0;
         }
     }
     else
     {
         num2 = (instanceName.Length + 1) * 2;
         totalSize += num2;
         num4 = this.CalculateAndAllocateMemory(totalSize, out num3);
     }
     long num8 = this.ResolveOffset(num4, totalSize + num3);
     if (num4 == this.InitialOffset)
     {
         entryPtr = (CategoryEntry*) num8;
         num8 += CategoryEntrySize + num3;
         entryPtr2 = (InstanceEntry*) num8;
     }
     else
     {
         num8 += num3;
         entryPtr = (CategoryEntry*) num8;
         num8 += CategoryEntrySize;
         entryPtr2 = (InstanceEntry*) num8;
     }
     num8 += InstanceEntrySize;
     CounterEntry* counterEntry = (CounterEntry*) num8;
     num8 += CounterEntrySize * this.categoryData.CounterNames.Count;
     if (this.categoryData.UseUniqueSharedMemory)
     {
         ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*) num8;
         num8 += ProcessLifetimeEntrySize;
         counterEntry->LifetimeOffset = (int) (((ulong) lifetimeEntry) - this.baseAddress);
         PopulateLifetimeEntry(lifetimeEntry, lifetime);
     }
     entryPtr->CategoryNameHashCode = this.categoryNameHashCode;
     entryPtr->NextCategoryOffset = 0;
     entryPtr->FirstInstanceOffset = (int) (((ulong) entryPtr2) - this.baseAddress);
     entryPtr->CategoryNameOffset = (int) (num8 - this.baseAddress);
     SafeMarshalCopy(this.categoryName, (IntPtr) num8);
     num8 += num;
     entryPtr2->InstanceNameHashCode = instanceNameHashCode;
     entryPtr2->NextInstanceOffset = 0;
     entryPtr2->FirstCounterOffset = (int) (((ulong) counterEntry) - this.baseAddress);
     entryPtr2->RefCount = 1;
     entryPtr2->InstanceNameOffset = (int) (num8 - this.baseAddress);
     SafeMarshalCopy(instanceName, (IntPtr) num8);
     num8 += num2;
     string wstr = (string) this.categoryData.CounterNames[0];
     counterEntry->CounterNameHashCode = GetWstrHashCode(wstr);
     SetValue(counterEntry, 0L);
     counterEntry->CounterNameOffset = (int) (num8 - this.baseAddress);
     SafeMarshalCopy(wstr, (IntPtr) num8);
     num8 += (wstr.Length + 1) * 2;
     for (int j = 1; j < this.categoryData.CounterNames.Count; j++)
     {
         CounterEntry* entryPtr5 = counterEntry;
         wstr = (string) this.categoryData.CounterNames[j];
         counterEntry++;
         counterEntry->CounterNameHashCode = GetWstrHashCode(wstr);
         SetValue(counterEntry, 0L);
         counterEntry->CounterNameOffset = (int) (num8 - this.baseAddress);
         SafeMarshalCopy(wstr, (IntPtr) num8);
         num8 += (wstr.Length + 1) * 2;
         entryPtr5->NextCounterOffset = (int) (((ulong) counterEntry) - this.baseAddress);
     }
     int num10 = (int) (((ulong) entryPtr) - this.baseAddress);
     lastCategoryPointer.IsConsistent = 0;
     if (num10 != this.InitialOffset)
     {
         lastCategoryPointer.NextCategoryOffset = num10;
     }
     if (this.categoryData.UseUniqueSharedMemory)
     {
         this.baseAddress[0] = num5;
         lastCategoryPointer.IsConsistent = 1;
     }
     return num10;
 }
 private unsafe bool TryReuseInstance(int instanceNameHashCode, string instanceName, CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference, PerformanceCounterInstanceLifetime lifetime, InstanceEntry* lockInstancePointer)
 {
     InstanceEntry* entryPtr = (InstanceEntry*) this.ResolveOffset(categoryPointer.FirstInstanceOffset, InstanceEntrySize);
     InstanceEntry* entryPtr2 = entryPtr;
 Label_0015:
     if (entryPtr->RefCount == 0)
     {
         bool flag;
         long num;
         if (this.categoryData.UseUniqueSharedMemory)
         {
             num = this.ResolveOffset(entryPtr->InstanceNameOffset, 0x100);
             flag = true;
         }
         else
         {
             num = this.ResolveOffset(entryPtr->InstanceNameOffset, 0);
             flag = this.GetStringLength((char*) num) == instanceName.Length;
         }
         bool flag2 = (lockInstancePointer == entryPtr) || this.categoryData.UseUniqueSharedMemory;
         if (flag)
         {
             bool flag3;
             if (flag2)
             {
                 flag3 = true;
             }
             else
             {
                 WaitAndEnterCriticalSection(&entryPtr->SpinLock, out flag3);
             }
             if (flag3)
             {
                 try
                 {
                     SafeMarshalCopy(instanceName, (IntPtr) num);
                     entryPtr->InstanceNameHashCode = instanceNameHashCode;
                     *((IntPtr*) returnInstancePointerReference) = entryPtr;
                     this.ClearCounterValues(returnInstancePointerReference[0]);
                     if (this.categoryData.UseUniqueSharedMemory)
                     {
                         CounterEntry* entryPtr3 = (CounterEntry*) this.ResolveOffset(entryPtr->FirstCounterOffset, CounterEntrySize);
                         ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*) this.ResolveOffset(entryPtr3->LifetimeOffset, ProcessLifetimeEntrySize);
                         PopulateLifetimeEntry(lifetimeEntry, lifetime);
                     }
                     *(((IntPtr*) returnInstancePointerReference)).RefCount = 1;
                     return true;
                 }
                 finally
                 {
                     if (!flag2)
                     {
                         ExitCriticalSection(&entryPtr->SpinLock);
                     }
                 }
             }
         }
     }
     entryPtr2 = entryPtr;
     if (entryPtr->NextInstanceOffset != 0)
     {
         entryPtr = (InstanceEntry*) this.ResolveOffset(entryPtr->NextInstanceOffset, InstanceEntrySize);
         goto Label_0015;
     }
     *((IntPtr*) returnInstancePointerReference) = entryPtr2;
     return false;
 }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes the performance counter component
        /// </summary>
        /// <param name="id">Unique identifier for a performance counter</param>
        /// <param name="categoryName">The category of performance counter</param>
        /// <param name="counterName">Name of the performance counter</param>
        /// <param name="instanceName">Performance counter instance</param>
        /// <param name="machineName"> The computer on which the performance counter and its associated                   category exists</param>
        /// <param name="counterLifeTime">Specifies the life time of performance counter instance</param>
        internal Counter(int id, string categoryName, string counterName, string instanceName, string machineName, PerformanceCounterInstanceLifetime counterLifeTime)
        {
            this.performanceCounter = new PerformanceCounter()
            {
                CategoryName     = categoryName,
                CounterName      = counterName,
                InstanceName     = instanceName,
                InstanceLifetime = counterLifeTime,
                MachineName      = machineName,
                ReadOnly         = false
            };

            this.ID = id;
        }
 private static unsafe void PopulateLifetimeEntry(ProcessLifetimeEntry* lifetimeEntry, PerformanceCounterInstanceLifetime lifetime)
 {
     if (lifetime == PerformanceCounterInstanceLifetime.Process)
     {
         lifetimeEntry.LifetimeType = 1;
         lifetimeEntry.ProcessId = ProcessData.ProcessId;
         lifetimeEntry.StartupTime = ProcessData.StartupTime;
     }
     else
     {
         lifetimeEntry.ProcessId = 0;
         lifetimeEntry.StartupTime = 0L;
     }
 }
        public static void TryCountPerformance
        (
            PerformanceCounterProcessingFlagsType enabledProcessingFlagsType
            , string categoryName
            , string instanceName
            , Func <bool> onGetEnableCountProcessFunc     = null
            , Action onCountPerformanceInnerProcessAction = null
            , Func <PerformanceCounterProcessingFlagsType, PerformanceCounter, long>
            onPerformanceCounterChangeValueProcessFunc = null
            , Func <Exception, Exception, string, bool>
            onCaughtExceptionProcessFunc = null
            , Action <bool, Exception, Exception, string>
            onFinallyProcessAction = null
            , PerformanceCounterInstanceLifetime
            instanceLifetime
            = PerformanceCounterInstanceLifetime.Global
            , long?initializeInstanceRawValue = null
        )
        {
            var enabledCountPerformance = true;

            Stopwatch[] stopwatches = null;
            var         container   = CountPerformanceBegin
                                      (
                enabledProcessingFlagsType
                , categoryName
                , instanceName
                , out enabledCountPerformance
                , out stopwatches
                , onGetEnableCountProcessFunc
                , onPerformanceCounterChangeValueProcessFunc
                , instanceLifetime
                , initializeInstanceRawValue
                                      );
            var reThrowException = false;

            #region Count Inner TryCatchFinally
            TryCatchFinallyProcessHelper
            .TryProcessCatchFinally
            (
                true
                , () =>
            {
                onCountPerformanceInnerProcessAction();
            }
                , reThrowException
                , (x, y, z) =>
            {
                container
                .CaughtExceptionsPerformanceCounter
                .Increment();
                var r = reThrowException;
                if (onCaughtExceptionProcessFunc != null)
                {
                    r = onCaughtExceptionProcessFunc
                        (
                        x
                        , y
                        , z
                        );
                }
                return(r);
            }
                , (x, y, z, w) =>
            {
                if (onFinallyProcessAction != null)
                {
                    onFinallyProcessAction
                    (
                        x
                        , y
                        , z
                        , w
                    );
                }
            }
            );
            #endregion

            if (enabledCountPerformance)
            {
                CountPerformanceEnd
                (
                    enabledProcessingFlagsType
                    , categoryName
                    , instanceName
                    , stopwatches
                    , onPerformanceCounterChangeValueProcessFunc
                );
            }
        }
 internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
 {
     if ((instanceName != null) && (instanceName.Length != 0))
     {
         CategoryEntry* entryPtr;
         int wstrHashCode = GetWstrHashCode(instanceName);
         if (this.FindCategory(&entryPtr))
         {
             InstanceEntry* returnInstancePointerReference = null;
             bool flag = false;
             Mutex mutex = null;
             RuntimeHelpers.PrepareConstrainedRegions();
             try
             {
                 bool flag2;
                 SharedUtils.EnterMutexWithoutGlobal(this.categoryData.MutexName, ref mutex);
                 if (this.thisInstanceOffset != -1)
                 {
                     try
                     {
                         returnInstancePointerReference = (InstanceEntry*) this.ResolveOffset(this.thisInstanceOffset, InstanceEntrySize);
                         if ((returnInstancePointerReference->InstanceNameHashCode == wstrHashCode) && this.StringEquals(instanceName, returnInstancePointerReference->InstanceNameOffset))
                         {
                             flag = true;
                             CounterEntry* entryPtr3 = (CounterEntry*) this.ResolveOffset(returnInstancePointerReference->FirstCounterOffset, CounterEntrySize);
                             if (this.categoryData.UseUniqueSharedMemory)
                             {
                                 ProcessLifetimeEntry* entryPtr4 = (ProcessLifetimeEntry*) this.ResolveOffset(entryPtr3->LifetimeOffset, ProcessLifetimeEntrySize);
                                 if (((entryPtr4 != null) && (entryPtr4->LifetimeType == 1)) && (entryPtr4->ProcessId != 0))
                                 {
                                     flag &= instanceLifetime == PerformanceCounterInstanceLifetime.Process;
                                     flag &= ProcessData.ProcessId == entryPtr4->ProcessId;
                                     if ((entryPtr4->StartupTime != -1L) && (ProcessData.StartupTime != -1L))
                                     {
                                         flag &= ProcessData.StartupTime == entryPtr4->StartupTime;
                                     }
                                 }
                                 else
                                 {
                                     flag &= instanceLifetime != PerformanceCounterInstanceLifetime.Process;
                                 }
                             }
                         }
                     }
                     catch (InvalidOperationException)
                     {
                         flag = false;
                     }
                     if (!flag)
                     {
                         this.thisInstanceOffset = -1;
                     }
                 }
                 if ((flag || this.FindInstance(wstrHashCode, instanceName, entryPtr, &returnInstancePointerReference, false, instanceLifetime, out flag2)) && (returnInstancePointerReference != null))
                 {
                     this.RemoveOneInstance(returnInstancePointerReference, false);
                 }
             }
             finally
             {
                 if (mutex != null)
                 {
                     mutex.ReleaseMutex();
                     mutex.Close();
                 }
             }
         }
     }
 }
        private unsafe int CreateInstance(CategoryEntry* categoryPointer, 
                                            int instanceNameHashCode, string instanceName, 
                                            PerformanceCounterInstanceLifetime lifetime) {
            int instanceNameLength;
            int totalSize = InstanceEntrySize +  (CounterEntrySize * categoryData.CounterNames.Count);
            int alignmentAdjustment;
            int freeMemoryOffset;
            int newOffset = 0;


            if (categoryData.UseUniqueSharedMemory) {
                instanceNameLength = InstanceNameSlotSize;
                totalSize += ProcessLifetimeEntrySize + instanceNameLength;

                // If we're in a separate shared memory, we need to do a two stage update of the free memory pointer.
                // First we calculate our alignment adjustment and where the new free offset is.  Then we 
                // write the new structs and data.  The last two operations are to link the new structs into the 
                // existing ones and update the next free offset.  Our process could get killed in between those two,
                // leaving the memory in an inconsistent state.  We use the "IsConsistent" flag to help determine 
                // when that has happened. 
                freeMemoryOffset = *((int *) baseAddress);
                newOffset = CalculateMemory(freeMemoryOffset, totalSize, out alignmentAdjustment);
            }
            else {
                instanceNameLength = (instanceName.Length +1) * 2;
                totalSize += instanceNameLength;

                // add in the counter names for the global shared mem.
                for (int i=0; i<categoryData.CounterNames.Count; i++) {
                    totalSize += (((string)categoryData.CounterNames[i]).Length + 1) * 2;
                }
                freeMemoryOffset = CalculateAndAllocateMemory(totalSize, out alignmentAdjustment);
            }

            freeMemoryOffset += alignmentAdjustment;
            long nextPtr = ResolveOffset(freeMemoryOffset, totalSize);    // don't add alignmentAdjustment since it's already
                                                                          // been added to freeMemoryOffset 

            InstanceEntry* newInstanceEntryPointer = (InstanceEntry*) nextPtr;
            nextPtr += InstanceEntrySize;

            // create the first CounterEntry and reserve space for all of the rest.  We won't 
            // finish creating them until the end
            CounterEntry* newCounterEntryPointer = (CounterEntry*) nextPtr;
            nextPtr += CounterEntrySize * categoryData.CounterNames.Count;
            
            if (categoryData.UseUniqueSharedMemory) {
                ProcessLifetimeEntry* newLifetimeEntry = (ProcessLifetimeEntry*) nextPtr;
                nextPtr += ProcessLifetimeEntrySize;
                
                newCounterEntryPointer->LifetimeOffset = (int)((long)newLifetimeEntry - baseAddress);
                PopulateLifetimeEntry(newLifetimeEntry, lifetime);
            }

            // set up the InstanceEntry
            newInstanceEntryPointer->InstanceNameHashCode = instanceNameHashCode;
            newInstanceEntryPointer->NextInstanceOffset = 0;
            newInstanceEntryPointer->FirstCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
            newInstanceEntryPointer->RefCount = 1;
            newInstanceEntryPointer->InstanceNameOffset = (int) (nextPtr - baseAddress);
            SafeMarshalCopy(instanceName, (IntPtr)nextPtr);

            nextPtr += instanceNameLength;


            if (categoryData.UseUniqueSharedMemory) {
                // in the unique shared mem we'll assume that the CounterEntries of the first instance
                // are all created.  Then we can just refer to the old counter name rather than copying in a new one.
                InstanceEntry* firstInstanceInCategoryPointer = (InstanceEntry*) ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize);
                CounterEntry* firstCounterInCategoryPointer = (CounterEntry*) ResolveOffset(firstInstanceInCategoryPointer->FirstCounterOffset, CounterEntrySize);
                newCounterEntryPointer->CounterNameHashCode = firstCounterInCategoryPointer->CounterNameHashCode;
                SetValue(newCounterEntryPointer, 0);
                newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;

                // now create the rest of the CounterEntrys
                CounterEntry* previousCounterEntryPointer;
                for (int i=1; i<categoryData.CounterNames.Count; i++) {
                    previousCounterEntryPointer = newCounterEntryPointer;
                    
                    newCounterEntryPointer++;
                    Debug.Assert(firstCounterInCategoryPointer->NextCounterOffset != 0, "The unique shared memory should have all of its counters created by the time we hit CreateInstance");
                    firstCounterInCategoryPointer = (CounterEntry*) ResolveOffset(firstCounterInCategoryPointer->NextCounterOffset, CounterEntrySize);
                    newCounterEntryPointer->CounterNameHashCode = firstCounterInCategoryPointer->CounterNameHashCode;
                    SetValue(newCounterEntryPointer, 0);
                    newCounterEntryPointer->CounterNameOffset = firstCounterInCategoryPointer->CounterNameOffset;

                    previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);
                }
            }
            else {
                // now create the rest of the CounterEntrys
                CounterEntry* previousCounterEntryPointer = null;
                for (int i=0; i<categoryData.CounterNames.Count; i++) {
                    string counterName = (string) categoryData.CounterNames[i];
                    newCounterEntryPointer->CounterNameHashCode = GetWstrHashCode(counterName);
                    newCounterEntryPointer->CounterNameOffset = (int) (nextPtr - baseAddress);
                    SafeMarshalCopy(counterName, (IntPtr)nextPtr);
                    nextPtr += (counterName.Length + 1) * 2;

                    SetValue(newCounterEntryPointer, 0);

                    if (i != 0)
                        previousCounterEntryPointer->NextCounterOffset = (int)((long)newCounterEntryPointer - baseAddress);

                    previousCounterEntryPointer = newCounterEntryPointer;
                    newCounterEntryPointer++;
                }
            }
            
            Debug.Assert(nextPtr - baseAddress == freeMemoryOffset + totalSize, "We should have used all of the space we requested at this point");

            int offset = (int) ((long) newInstanceEntryPointer - baseAddress);
            categoryPointer->IsConsistent = 0;
            
            // prepend the new instance rather than append, helps with perf of hooking up subsequent counters 
            newInstanceEntryPointer->NextInstanceOffset = categoryPointer->FirstInstanceOffset;
            categoryPointer->FirstInstanceOffset = offset;

            if (categoryData.UseUniqueSharedMemory) {
                *((int*) baseAddress) = newOffset;
                categoryPointer->IsConsistent = 1;
            }

            return freeMemoryOffset;
        }
Exemplo n.º 31
0
        internal static PerformanceCounter GetPerformanceCounterInternal(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;

            try
            {
                counter = new PerformanceCounter {
                    CategoryName     = categoryName,
                    CounterName      = perfCounterName,
                    InstanceName     = instanceName,
                    ReadOnly         = false,
                    InstanceLifetime = instanceLifetime
                };
                try
                {
                    long rawValue = counter.RawValue;
                }
                catch (InvalidOperationException)
                {
                    counter = null;
                    throw;
                }
                catch (SecurityException exception)
                {
                    if (MinimalPerformanceCountersEnabled)
                    {
                        scope = PerformanceCounterScope.Off;
                    }
                    if (DiagnosticUtility.ShouldTraceWarning)
                    {
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(new SecurityException(System.ServiceModel.SR.GetString("PartialTrustPerformanceCountersNotEnabled"), exception), TraceEventType.Warning);
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(System.ServiceModel.SR.GetString("PartialTrustPerformanceCountersNotEnabled")));
                }
            }
            catch (Exception exception2)
            {
                if (Fx.IsFatal(exception2))
                {
                    throw;
                }
                if (counter != null)
                {
                    if (!counter.ReadOnly)
                    {
                        try
                        {
                            counter.RemoveInstance();
                        }
                        catch (Exception exception3)
                        {
                            if (Fx.IsFatal(exception3))
                            {
                                throw;
                            }
                        }
                    }
                    counter = null;
                }
                bool flag = true;
                if (categoryName == "ServiceModelService 4.0.0.0")
                {
                    if (!serviceOOM)
                    {
                        serviceOOM = true;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                else if (categoryName == "ServiceModelOperation 4.0.0.0")
                {
                    if (!operationOOM)
                    {
                        operationOOM = true;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                else if (categoryName == "ServiceModelEndpoint 4.0.0.0")
                {
                    if (!endpointOOM)
                    {
                        endpointOOM = true;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                if (flag)
                {
                    DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.PerformanceCounter, (EventLogEventId)(-1073610742), new string[] { categoryName, perfCounterName, exception2.ToString() });
                }
            }
            return(counter);
        }
        private unsafe CounterEntry* GetCounter(string counterName, string instanceName, bool enableReuse, PerformanceCounterInstanceLifetime lifetime) {
            int counterNameHashCode = GetWstrHashCode(counterName);
            int instanceNameHashCode;
            if (instanceName != null && instanceName.Length != 0)
                instanceNameHashCode = GetWstrHashCode(instanceName);
            else {
                instanceNameHashCode = SingleInstanceHashCode;
                instanceName = SingleInstanceName;
            }

            Mutex mutex = null;
            CounterEntry* counterPointer = null;
            InstanceEntry* instancePointer = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex);
                CategoryEntry* categoryPointer;
                bool counterFound = false;
                while (!FindCategory(&categoryPointer)) {
                    // don't bother locking again if we're using a separate shared memory.  
                    bool sectionEntered;
                    if (categoryData.UseUniqueSharedMemory)
                        sectionEntered = true;
                    else
                        WaitAndEnterCriticalSection(&(categoryPointer->SpinLock), out sectionEntered);

                    int newCategoryOffset;
                    if (sectionEntered) {
                        try {
                            newCategoryOffset = CreateCategory(categoryPointer, instanceNameHashCode, instanceName, lifetime);
                        }
                        finally {
                            if (!categoryData.UseUniqueSharedMemory)
                                ExitCriticalSection(&(categoryPointer->SpinLock));
                        }

                        categoryPointer = (CategoryEntry*)(ResolveOffset(newCategoryOffset, CategoryEntrySize));
                        instancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
                        counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
                        Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
                        return counterPointer;
                    }
                }

                bool foundFreeInstance;
                while (!FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, true, lifetime, out foundFreeInstance)) {
                    InstanceEntry* lockInstancePointer = instancePointer;
                    
                    // don't bother locking again if we're using a separate shared memory.  
                    bool sectionEntered;
                    if (categoryData.UseUniqueSharedMemory)
                        sectionEntered = true;
                    else
                        WaitAndEnterCriticalSection(&(lockInstancePointer->SpinLock), out sectionEntered);
                    
                    if (sectionEntered) {
                        try {
                            bool reused = false;

                            if (enableReuse && foundFreeInstance) {
                                reused = TryReuseInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, lifetime, lockInstancePointer);
                                // at this point we might have reused an instance that came from v1.1/v1.0.  We can't assume it will have the counter
                                // we're looking for. 
                            }

                            if (!reused) {
                                int newInstanceOffset = CreateInstance(categoryPointer, instanceNameHashCode, instanceName, lifetime);
                                instancePointer = (InstanceEntry*)(ResolveOffset(newInstanceOffset, InstanceEntrySize));

                                counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
                                Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
                                return counterPointer;
                            }
                        }
                        finally {
                            if (!categoryData.UseUniqueSharedMemory)
                                ExitCriticalSection(&(lockInstancePointer->SpinLock));
                        }
                    }
                }

                if (categoryData.UseUniqueSharedMemory) {
                    counterFound = FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer);
                    Debug.Assert(counterFound, "All counters should be created, so we should always find the counter");
                    return counterPointer;
                }
                else {
                    while (!FindCounter(counterNameHashCode, counterName, instancePointer, &counterPointer)) {
                        bool sectionEntered;
                        WaitAndEnterCriticalSection(&(counterPointer->SpinLock), out sectionEntered);
                        
                        if (sectionEntered) {
                            try {
                                int newCounterOffset =  CreateCounter(counterPointer, counterNameHashCode, counterName);
                                return (CounterEntry*) (ResolveOffset(newCounterOffset, CounterEntrySize));
                            }
                            finally {
                                ExitCriticalSection(&(counterPointer->SpinLock));
                            }
                        }
                    }
                    
                    return counterPointer;
                }
            }
            finally {
                // cache this instance for reuse 
                try {
                    if (counterPointer != null && instancePointer != null) {
                        this.thisInstanceOffset = ResolveAddress((long)instancePointer, InstanceEntrySize);
                    }
                }
                catch (InvalidOperationException) {
                    this.thisInstanceOffset = -1;
                }

                if (mutex != null) {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
Exemplo n.º 33
0
        internal static PerformanceCounter GetPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;

            if (!PerformanceCountersEnabled && !MinimalPerformanceCountersEnabled)
            {
                return(counter);
            }
            return(GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime));
        }
        internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime) {
            this.categoryName = catName;
            this.categoryNameHashCode = GetWstrHashCode(categoryName);

            categoryData = GetCategoryData();

            // Check that the instance name isn't too long if we're using the new shared memory.  
            // We allocate InstanceNameSlotSize bytes in the shared memory
            if (categoryData.UseUniqueSharedMemory) {
                if (instanceName != null && instanceName.Length > InstanceNameMaxLength)
                    throw new InvalidOperationException(SR.GetString(SR.InstanceNameTooLong));
            }
            else {
                if (lifetime != PerformanceCounterInstanceLifetime.Global)
                    throw new InvalidOperationException(SR.GetString(SR.ProcessLifetimeNotValidInGlobal));
            }

            if (counterName != null && instanceName != null) {
                if (!categoryData.CounterNames.Contains(counterName))
                    Debug.Assert(false, "Counter " + counterName + " does not exist in category " + catName);
                else
                    this.counterEntryPointer = GetCounter(counterName, instanceName, categoryData.EnableReuse, lifetime);
            }
        }
        /// <summary>
        /// In this method we instantiate the PerformanceCounter object and return it.
        /// </summary>
        /// <param name="categoryName">Category name</param>
        /// <param name="counterName">Counter name</param>
        /// <param name="instanceName">Counter instance name</param>
        /// <param name="instanceLifeTime">The life time of this instance</param>
        /// <param name="readOnly">Is counter for read only?</param>
        /// <returns>Performance counter</returns>
        public static PerformanceCounter getCounter(
            string categoryName,
            string counterName,
            string instanceName,
            PerformanceCounterInstanceLifetime instanceLifeTime,
            bool readOnly
        ) {

            PerformanceCounter counter = null;

            // Check if the category exists
            if (PerformanceCounterCategory.Exists(categoryName)) {
                counter =
                    new PerformanceCounter(
                        categoryName,
                        counterName,
                        instanceName,
                        readOnly
                    );
            }
            
            return counter;
        }
        static internal PerformanceCounter GetPerformanceCounterInternal(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;
            try
            {
                counter = new PerformanceCounter();
                counter.CategoryName = categoryName;
                counter.CounterName = perfCounterName;
                counter.InstanceName = instanceName;
                counter.ReadOnly = false;
                counter.InstanceLifetime = instanceLifetime;

                // We now need to access the counter raw data to
                // force the counter object to be initialized.  This
                // will force any exceptions due to mis-installation
                // of counters to occur here and be traced appropriately.
                try
                {
                    long rawValue = counter.RawValue;
                }
                catch (InvalidOperationException)
                {
                    counter = null;
                    throw;
                }
                catch (SecurityException securityException)
                {
                    // Cannot access performance counter due to partial trust scenarios
                    // Disable the default performance counters' access otherwise
                    // in PT the service will be broken
                    PerformanceCounters.scope = PerformanceCounterScope.Off;

                    DiagnosticUtility.TraceHandledException(new SecurityException(SR.GetString(
                                SR.PartialTrustPerformanceCountersNotEnabled), securityException), TraceEventType.Warning);
                    
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityException(SR.GetString(
                                SR.PartialTrustPerformanceCountersNotEnabled)));
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (null != counter)
                {
                    if (!counter.ReadOnly)
                    {
                        try
                        {
                            counter.RemoveInstance();
                        }
                        // Already inside a catch block for a failure case
                        // ok to ---- any exceptions here and trace the
                        // original failure.
#pragma warning suppress 56500 // covered by FxCOP
                        catch (Exception e1)
                        {
                            if (Fx.IsFatal(e1))
                            {
                                throw;
                            }
                        }
                    }

                    counter = null;
                }
                bool logEvent = true;
                if (categoryName == PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters)
                {
                    if (serviceOOM == false)
                    {
                        serviceOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }
                else if (categoryName == PerformanceCounterStrings.SERVICEMODELOPERATION.OperationPerfCounters)
                {
                    if (operationOOM == false)
                    {
                        operationOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }
                else if (categoryName == PerformanceCounterStrings.SERVICEMODELENDPOINT.EndpointPerfCounters)
                {
                    if (endpointOOM == false)
                    {
                        endpointOOM = true;
                    }
                    else
                    {
                        logEvent = false;
                    }
                }

                if (logEvent)
                {
                    DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                                             (ushort)System.Runtime.Diagnostics.EventLogCategory.PerformanceCounter,
                                             (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToLoadPerformanceCounter,
                                             categoryName,
                                             perfCounterName,
                                             e.ToString());
                }
            }
            return counter;
        }
Exemplo n.º 37
0
 static PerformanceCounter GetListenerPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
 {
     return PerformanceCounters.GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime);
 }
Exemplo n.º 38
0
        public ChoPerformanceCounter(string categoryName, string counterName, PerformanceCounterType counterType, string instanceName, string machineName, bool readOnly, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            if (instanceName == ChoPerformanceCounter.DefaultInstanceName)
            {
                _performanceCounter             = new PerformanceCounter(categoryName, counterName);
                _performanceCounter.MachineName = machineName;
            }
            else
            {
                _performanceCounter = new PerformanceCounter(categoryName, counterName, instanceName, machineName);
            }

            _performanceCounter.ReadOnly         = readOnly;
            _performanceCounter.InstanceLifetime = instanceLifetime;

            // create base counter if needed
            switch (counterType)
            {
            case PerformanceCounterType.AverageCount64:
            case PerformanceCounterType.AverageTimer32:
            case PerformanceCounterType.RawFraction:
            case PerformanceCounterType.CounterMultiTimer:
            case PerformanceCounterType.CounterMultiTimerInverse:
            case PerformanceCounterType.CounterMultiTimer100Ns:
            case PerformanceCounterType.CounterMultiTimer100NsInverse:
            case PerformanceCounterType.SampleCounter:
            case PerformanceCounterType.SampleFraction:
            {
                if (instanceName == ChoPerformanceCounter.DefaultInstanceName)
                {
                    _performanceCounterBase             = new PerformanceCounter(categoryName, ChoPerformanceCounter.GetBaseCounterName(counterName));
                    _performanceCounterBase.MachineName = machineName;
                }
                else
                {
                    _performanceCounterBase = new PerformanceCounter(categoryName, ChoPerformanceCounter.GetBaseCounterName(counterName), instanceName, machineName);
                }

                _performanceCounterBase.ReadOnly         = ReadOnly;
                _performanceCounterBase.InstanceLifetime = instanceLifetime;
                break;
            }

            default:
                break;
            }

            _metaDataInfo = new ChoPCMetaDataInfo(CounterName, instanceName)
            {
                TurnOn = true
            };
            ChoPCMetaDataManager.Me.SetWatcher(this);
        }
Exemplo n.º 39
0
        public static Stopwatch CountPerformanceBegin
        (
            MultiPerformanceCountersTypeFlags enabledPerformanceCounters
            , string performanceCountersCategoryName
            , string performanceCountersCategoryInstanceName
            , Func <bool> onEnabledCountPerformanceProcessFunc = null
            , PerformanceCounterInstanceLifetime
            performanceCounterInstanceLifetime
            = PerformanceCounterInstanceLifetime.Global
            , long?initializePerformanceCounterInstanceRawValue = null
        )
        {
            Stopwatch r = null;
            var       enabledCountPerformance = true;

            {
                if (onEnabledCountPerformanceProcessFunc != null)
                {
                    enabledCountPerformance = onEnabledCountPerformanceProcessFunc.Invoke();
                }
            }
            if
            (
                enabledCountPerformance
                &&
                enabledPerformanceCounters != MultiPerformanceCountersTypeFlags.None
            )
            {
                string key = string
                             .Format
                             (
                    "{1}{0}{2}"
                    , "-"
                    , performanceCountersCategoryName
                    , performanceCountersCategoryInstanceName
                             );
                TPerformanceCountersContainer container = null;
                if (!_dictionary.TryGetValue(key, out container))
                {
                    lock (_lockerObject)
                    {
                        container = new TPerformanceCountersContainer();
                        _dictionary.Add
                        (
                            key
                            , container
                        );
                        container
                        .AttachPerformanceCountersToMembers
                        (
                            performanceCountersCategoryName
                            , performanceCountersCategoryInstanceName
                            , performanceCounterInstanceLifetime
                            , initializePerformanceCounterInstanceRawValue
                        );
                    }
                }
                var enableProcessCounter = enabledPerformanceCounters
                                           .HasFlag
                                           (
                    MultiPerformanceCountersTypeFlags
                    .ProcessCounter
                                           );
                if (enableProcessCounter)
                {
                    container
                    .PrcocessPerformanceCounter
                    .Increment();
                }
                var enableProcessingCounter = enabledPerformanceCounters
                                              .HasFlag
                                              (
                    MultiPerformanceCountersTypeFlags
                    .ProcessingCounter
                                              );
                if (enableProcessingCounter)
                {
                    container.ProcessingPerformanceCounter.Increment();
                }
                var enableProcessedAverageTimerCounter
                    = enabledPerformanceCounters
                      .HasFlag
                      (
                          MultiPerformanceCountersTypeFlags
                          .ProcessedAverageTimerCounter
                      );
                if (enableProcessedAverageTimerCounter)
                {
                    _stopwatchsPool.TryGet(out r); //Stopwatch.StartNew();
                    r.Restart();
                }
            }
            return(r);
        }
Exemplo n.º 40
0
        static internal PerformanceCounter GetPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime)
        {
            PerformanceCounter counter = null;

            if (PerformanceCounters.PerformanceCountersEnabled || PerformanceCounters.MinimalPerformanceCountersEnabled)
            {
                counter = PerformanceCounters.GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime);
            }

            return(counter);
        }
        private unsafe bool TryReuseInstance(int instanceNameHashCode, string instanceName, 
                                               CategoryEntry* categoryPointer, InstanceEntry** returnInstancePointerReference, 
                                               PerformanceCounterInstanceLifetime lifetime,
                                               InstanceEntry* lockInstancePointer) {
            //
            // 2nd pass find a free instance slot
            // 
            InstanceEntry* currentInstancePointer = (InstanceEntry*)(ResolveOffset(categoryPointer->FirstInstanceOffset, InstanceEntrySize));
            InstanceEntry* previousInstancePointer = currentInstancePointer;
            for (;;) {
                if (currentInstancePointer->RefCount == 0) {

                    bool hasFit;
                    long instanceNamePtr;       // we need cache this to avoid race conditions. 
                    
                    if (categoryData.UseUniqueSharedMemory) {
                        instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, InstanceNameSlotSize);
                        // In the separate shared memory case we should always have enough space for instances.  The
                        // name slot size is fixed. 
                        Debug.Assert(((instanceName.Length + 1) * 2) <= InstanceNameSlotSize, "The instance name length should always fit in our slot size");
                        hasFit = true;
                    }
                    else {
                        // we don't know the string length yet. 
                        instanceNamePtr = ResolveOffset(currentInstancePointer->InstanceNameOffset, 0);

                        // In the global shared memory, we require names to be exactly the same length in order
                        // to reuse them.  This way we don't end up leaking any space and we don't need to 
                        // depend on the layout of the memory to calculate the space we have. 
                        int length = GetStringLength((char*) instanceNamePtr);
                        hasFit = (length == instanceName.Length);
                    }

                    bool noSpinLock = (lockInstancePointer == currentInstancePointer) || categoryData.UseUniqueSharedMemory;
                    // Instance name fit
                    if (hasFit) {
                        // don't bother locking again if we're using a separate shared memory.  
                        bool sectionEntered;
                        if (noSpinLock)
                            sectionEntered = true;
                        else
                            WaitAndEnterCriticalSection(&(currentInstancePointer->SpinLock), out sectionEntered);

                        if (sectionEntered) {
                            try {
                                // Make copy with zero-term
                                SafeMarshalCopy(instanceName, (IntPtr)instanceNamePtr);
                                currentInstancePointer->InstanceNameHashCode = instanceNameHashCode;

                                // return
                                *returnInstancePointerReference = currentInstancePointer;
                                // clear the counter values. 
                                ClearCounterValues(*returnInstancePointerReference);

                                if (categoryData.UseUniqueSharedMemory) {
                                    CounterEntry* counterPointer = (CounterEntry*)ResolveOffset(currentInstancePointer->FirstCounterOffset, CounterEntrySize);
                                    ProcessLifetimeEntry* lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(counterPointer->LifetimeOffset, ProcessLifetimeEntrySize);
                                    PopulateLifetimeEntry(lifetimeEntry, lifetime);
                                }
                                
                                (*returnInstancePointerReference)->RefCount = 1;
                                return true;
                            }
                            finally {
                                if (!noSpinLock)
                                    ExitCriticalSection(&(currentInstancePointer->SpinLock));
                            }
                        }
                    }
                 }
            
                previousInstancePointer = currentInstancePointer;
                if (currentInstancePointer->NextInstanceOffset != 0)
                    currentInstancePointer = (InstanceEntry*)(ResolveOffset(currentInstancePointer->NextInstanceOffset, InstanceEntrySize));
                else
                {
                    *returnInstancePointerReference = previousInstancePointer;
                    return false;
                }
            }
        }
 public override void AttachPerformanceCountersToMembers
                         (
                             string categoryName
                             , string instanceName
                             , PerformanceCounterInstanceLifetime
                                     performanceCounterInstanceLifetime = PerformanceCounterInstanceLifetime.Global
                             , long? initializePerformanceCounterInstanceRawValue = null
                         )
 {
     if (!_isAttachedPerformanceCounters)
     {
         //var type = this.GetType();
         AttachPerformanceCountersToMembers<QueuePerformanceCountersContainer>
                 (
                     categoryName
                     , instanceName
                     , this
                     , performanceCounterInstanceLifetime
                     , initializePerformanceCounterInstanceRawValue
                 );
     }
     _isAttachedPerformanceCounters = true;
 }
        internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInstanceLifetime instanceLifetime) {
             if (instanceName == null || instanceName.Length == 0)
                return;

            int instanceNameHashCode = GetWstrHashCode(instanceName);
            
            CategoryEntry* categoryPointer;
            if (!FindCategory(&categoryPointer)) 
                return;
            
            InstanceEntry* instancePointer = null;
            bool validatedCachedInstancePointer = false;
            bool temp;

            Mutex mutex = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutexWithoutGlobal(categoryData.MutexName, ref mutex); 
                
                if (this.thisInstanceOffset != -1) {
                    try {
                        // validate whether the cached instance pointer is pointing at the right instance  
                        instancePointer = (InstanceEntry*)(ResolveOffset(this.thisInstanceOffset, InstanceEntrySize));
                        if (instancePointer->InstanceNameHashCode == instanceNameHashCode) {
                            if (StringEquals(instanceName, instancePointer->InstanceNameOffset)){
                                validatedCachedInstancePointer = true;

                                // this is probably overkill
                                CounterEntry* firstCounter = (CounterEntry*) ResolveOffset(instancePointer->FirstCounterOffset, CounterEntrySize);
                                ProcessLifetimeEntry* lifetimeEntry;
                                if (categoryData.UseUniqueSharedMemory) {
                                    lifetimeEntry = (ProcessLifetimeEntry*) ResolveOffset(firstCounter->LifetimeOffset, ProcessLifetimeEntrySize);
                                    if (lifetimeEntry != null 
                                        && lifetimeEntry->LifetimeType == (int)PerformanceCounterInstanceLifetime.Process 
                                        && lifetimeEntry->ProcessId != 0) {
                                        validatedCachedInstancePointer &= (instanceLifetime == PerformanceCounterInstanceLifetime.Process);
                                        validatedCachedInstancePointer &= (ProcessData.ProcessId == lifetimeEntry->ProcessId);
                                        if ((lifetimeEntry->StartupTime != -1) && (ProcessData.StartupTime != -1))  
                                            validatedCachedInstancePointer &= (ProcessData.StartupTime == lifetimeEntry->StartupTime);
                                    }
                                    else 
                                        validatedCachedInstancePointer &= (instanceLifetime != PerformanceCounterInstanceLifetime.Process);
                                }
                            }
                        }
                    }
                    catch (InvalidOperationException) {
                        validatedCachedInstancePointer = false;
                    }
                    if (!validatedCachedInstancePointer) 
                        this.thisInstanceOffset = -1;
                }
                
                if (!validatedCachedInstancePointer && !FindInstance(instanceNameHashCode, instanceName, categoryPointer, &instancePointer, false, instanceLifetime, out temp)) 
                    return ;

                if (instancePointer != null)
                    RemoveOneInstance(instancePointer, false);
            }
            finally {
                if (mutex != null) {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
Exemplo n.º 44
0
        public void AttachPerformanceCountersCategoryInstance
        (
            string performanceCountersCategoryNamePrefix
            , string performanceCountersCategoryInstanceNamePrefix
            , Func <bool> onGetEnabledCountPerformanceProcessFunc = null
            , PerformanceCounterInstanceLifetime
            performanceCounterInstanceLifetime
            = PerformanceCounterInstanceLifetime.Process
        )
        {
            var process            = Process.GetCurrentProcess();
            var processName        = process.ProcessName;
            var instanceNamePrefix = string
                                     .Format
                                     (
                "{0}-{1}"
                , processName
                , performanceCountersCategoryInstanceNamePrefix
                                     );

            instanceNamePrefix = performanceCountersCategoryInstanceNamePrefix;
            var suffix = "-Queue";

            _performanceCountersCategoryNameForQueueProcess         = performanceCountersCategoryNamePrefix + suffix;
            _performanceCountersCategoryInstanceNameForQueueProcess = instanceNamePrefix + suffix;



            var qpcc = _queuePerformanceCountersContainer;

            qpcc
            .AttachPerformanceCountersToMembers
            (
                _performanceCountersCategoryNameForQueueProcess
                , _performanceCountersCategoryInstanceNameForQueueProcess
                , performanceCounterInstanceLifetime
            );
            qpcc
            .RegisterCountersUsage();

            suffix = "-BatchProcess";

            _performanceCountersCategoryNameForBatchProcess         = performanceCountersCategoryNamePrefix + suffix;
            _performanceCountersCategoryInstanceNameForBatchProcess = instanceNamePrefix + suffix;
            CommonPerformanceCountersContainer container = null;

            EasyPerformanceCountersHelper <CommonPerformanceCountersContainer>
            .AttachPerformanceCountersCategoryInstance
            (
                _performanceCountersCategoryNameForBatchProcess
                , _performanceCountersCategoryInstanceNameForBatchProcess
                , out container
                , performanceCounterInstanceLifetime
            );

            if (_timerCounters == null)
            {
                _timerCounters = new WriteableTuple
                                 <
                    bool
                    , Stopwatch
                    , PerformanceCounter
                    , PerformanceCounter
                                 >[]
                {
                    WriteableTuple
                    .Create
                    <
                        bool
                        , Stopwatch
                        , PerformanceCounter
                        , PerformanceCounter
                    >
                    (
                        false
                        , null
                        , _queuePerformanceCountersContainer
                        .QueuedWaitAverageTimerPerformanceCounter
                        , _queuePerformanceCountersContainer
                        .QueuedWaitAverageBasePerformanceCounter
                    )
                    , WriteableTuple
                    .Create
                    <
                        bool
                        , Stopwatch
                        , PerformanceCounter
                        , PerformanceCounter
                    >
                    (
                        true
                        , null
                        , _queuePerformanceCountersContainer
                        .DequeueProcessedAverageTimerPerformanceCounter
                        , _queuePerformanceCountersContainer
                        .DequeueProcessedAverageBasePerformanceCounter
                    )
                };
            }


            _isAttachedPerformanceCounters          = true;
            OnGetEnabledCountPerformanceProcessFunc = onGetEnabledCountPerformanceProcessFunc;
        }
        CountPerformanceBegin
        (
            PerformanceCounterProcessingFlagsType
            enabledProcessingFlagsType
            , string categoryName
            , string instanceName
            , out bool enabledCount
            , out Stopwatch[] stopwatches
            , Func <bool>
            onGetEnableCountProcessFunc = null
            , Func <PerformanceCounterProcessingFlagsType, PerformanceCounter, long>
            onPerformanceCounterChangeValueProcessFunc = null
            , PerformanceCounterInstanceLifetime
            instanceLifetime
            = PerformanceCounterInstanceLifetime.Global
            , long?initializeInstanceRawValue = null
        )
        {
            TPerformanceCountersContainer container = null;

            Stopwatch[] stopwatchesInline = null;
            enabledCount = true;
            {
                if (onGetEnableCountProcessFunc != null)
                {
                    enabledCount
                        = onGetEnableCountProcessFunc();
                }
            }
            if
            (
                enabledCount
                &&
                enabledProcessingFlagsType
                !=
                PerformanceCounterProcessingFlagsType.None
            )
            {
                var enableTimeBasedOnBeginOnEnd = false;
                PerformanceCountersPair[] performanceCountersPairs = null;
                var stopwatchIndex = 0;
                if (enabledCount)
                {
                    #region get Container
                    string key = string
                                 .Format
                                 (
                        "{1}{0}{2}"
                        , "-"
                        , categoryName
                        , instanceName
                                 );
                    if (!_dictionary.TryGetValue(key, out container))
                    {
                        lock (_lockerObject)
                        {
                            container = new TPerformanceCountersContainer();
                            _dictionary
                            .Add
                            (
                                key
                                , container
                            );
                            container
                            .AttachPerformanceCountersToMembers
                            (
                                categoryName
                                , instanceName
                            );
                        }
                    }
                    #endregion
                    var enableIncrementOnBegin
                        = enabledProcessingFlagsType
                          .HasFlag
                          (
                              PerformanceCounterProcessingFlagsType
                              .IncrementOnBegin
                          );
                    if (enableIncrementOnBegin)
                    {
                        Array
                        .ForEach
                        (
                            container
                            .IncrementOnBeginPerformanceCounters
                            , (x) =>
                        {
                            var increment = 1L;
                            if (onPerformanceCounterChangeValueProcessFunc != null)
                            {
                                increment = onPerformanceCounterChangeValueProcessFunc
                                            (
                                    PerformanceCounterProcessingFlagsType.IncrementOnBegin
                                    , x
                                            );
                            }
                            if (increment == 1)
                            {
                                x.Increment();
                            }
                            else
                            {
                                x.IncrementBy(increment);
                            }
                        }
                        );
                    }
                    enableTimeBasedOnBeginOnEnd
                        = enabledProcessingFlagsType
                          .HasFlag
                          (
                              PerformanceCounterProcessingFlagsType
                              .TimeBasedOnBeginOnEnd
                          );
                    if (enableTimeBasedOnBeginOnEnd)
                    {
                        performanceCountersPairs
                            = container
                              .TimeBasedOnBeginOnEndPerformanceCountersPairs;
                        stopwatchesInline = new Stopwatch[performanceCountersPairs.Length];
                        Array
                        .ForEach
                        (
                            performanceCountersPairs
                            , (x) =>
                        {
                            var stopwatch = _stopwatchsPool.Get();
                            stopwatchesInline[stopwatchIndex++] = stopwatch;
                            stopwatch.Restart();
                        }
                        );
                    }
                }
            }
            stopwatches = stopwatchesInline;
            return(container);
        }