示例#1
0
        private void Initialize(object state)
        {
            if (Logging.On) Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialization_started));

            PerformanceCounterPermission perfCounterPermission = new PerformanceCounterPermission(PermissionState.Unrestricted);
            perfCounterPermission.Assert();
            try
            {
                if (!PerformanceCounterCategory.Exists(categoryName))
                {
                    // if the perf. counter category doesn't exist, just log this information and exit.
                    if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_perfcounter_nocategory, categoryName));
                    return;
                }

                string instanceName = GetInstanceName();

                Debug.Assert(counterNames.Length == Enum.GetValues(typeof(NetworkingPerfCounterName)).Length,
                    "The number of NetworkingPerfCounterName items must match the number of CounterNames");

                // create the counters, this will check for the right permissions (false)
                // means the counter is not readonly (it's read/write) and cache them while
                // we're under the Assert(), which will be reverted in the finally below.
                counters = new CounterPair[counterNames.Length];
                for (int i = 0; i < counterNames.Length; i++)
                {
                    counters[i] = CreateCounterPair(counterNames[i], instanceName);
                }

                AppDomain.CurrentDomain.DomainUnload += new EventHandler(UnloadEventHandler);
                AppDomain.CurrentDomain.ProcessExit += new EventHandler(ExitEventHandler);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionEventHandler);

                initSuccessful = true;
            }
            catch (Win32Exception e)
            {
                if (Logging.On) Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", e);
                Cleanup();
                return;
            }
            catch (InvalidOperationException e)
            {
                if (Logging.On) Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", e);
                Cleanup();
                return;
            }
            finally
            {
                PerformanceCounterPermission.RevertAssert();

                initDone = true;

                if (Logging.On)
                {
                    if (initSuccessful)
                    {
                        Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialized_success));
                    }
                    else
                    {
                        Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialized_error));
                    }
                }
            }
        }