Ejemplo n.º 1
0
        private static IObservable <Counters> CreatePerformanceCountersAsync()
        {
            return(Observable.Create <Counters>(x =>
            {
                var disposable = new CompositeDisposable();

                try
                {
                    var processName = GetProcessInstanceName();

                    Logger.Info(
                        "Creating performance counter 'Working Set'");

                    var workingSetCounter =
                        new PerformanceCounter("Process",
                                               "Working Set", processName);
                    disposable.Add(workingSetCounter);

                    Logger.Info(
                        "Creating performance counter '% Processor Time'");

                    var cpuCounter =
                        new PerformanceCounter("Process",
                                               "% Processor Time", processName);
                    disposable.Add(cpuCounter);

                    using (
                        Duration.Measure(Logger,
                                         "Initialising performance counters (after creation)")
                        )
                    {
                        workingSetCounter.NextValue();
                        cpuCounter.NextValue();
                    }

                    x.OnNext(new Counters(workingSetCounter,
                                          cpuCounter));

                    Logger.Info("Ready");
                }
                catch (ArgumentException exn)
                {
                    LogFailToCreatePerformanceCounter(x, exn);
                }
                catch (InvalidOperationException exn)
                {
                    LogFailToCreatePerformanceCounter(x, exn);
                }
                catch (Win32Exception exn)
                {
                    LogFailToCreatePerformanceCounter(x, exn);
                }
                catch (PlatformNotSupportedException exn)
                {
                    LogFailToCreatePerformanceCounter(x, exn);
                }
                catch (UnauthorizedAccessException exn)
                {
                    LogFailToCreatePerformanceCounter(x, exn);
                }

                return disposable;
            }));
        }