NextSample() public method

public NextSample ( ) : System.Diagnostics.CounterSample
return System.Diagnostics.CounterSample
Exemplo n.º 1
0
        public void WatchCpuAndMemory()
        {
            var pc = new PerformanceCounter("Processor Information", "% Processor Time");
            var cat = new PerformanceCounterCategory("Processor Information");
            var cpuInstances = cat.GetInstanceNames();
            var cpus = new Dictionary<string, CounterSample>();

            var memoryCounter = new PerformanceCounter("Memory", "Available MBytes");

            foreach (var s in cpuInstances)
            {
                pc.InstanceName = s;
                cpus.Add(s, pc.NextSample());
            }
            var t = DateTime.Now;
            while (t.AddMinutes(1) > DateTime.Now)
            {
                Trace.WriteLine(string.Format("Memory:{0}MB", memoryCounter.NextValue()));

                foreach (var s in cpuInstances)
                {
                    pc.InstanceName = s;
                    Trace.WriteLine(string.Format("CPU:{0} - {1:f}", s, Calculate(cpus[s], pc.NextSample())));
                    cpus[s] = pc.NextSample();
                }

                //Trace.Flush();
                System.Threading.Thread.Sleep(1000);
            }
        }
        protected void FirePerfCounter(string category, string counterName, PerfCounterEventDelegate action)
        {
            PerformanceCounter counter = new PerformanceCounter(category, counterName, "_total_");
            CounterSample sample = counter.NextSample();
            float startVal = sample.RawValue;

            action();
            action();
            action();

            sample = counter.NextSample();
            float endVal = sample.RawValue;

            Assert.AreEqual(startVal + 3, endVal);
        }
Exemplo n.º 3
0
        public ActionResult CpuUtilization()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter
            {
                CategoryName = "Processor",
                CounterName = "% Processor Time",
                InstanceName = "_Total"
            };

            var sample1 = cpuCounter.NextSample();
            System.Threading.Thread.Sleep(100);
            var sample2 = cpuCounter.NextSample();
            var finalCpuCounter = CounterSample.Calculate(sample1, sample2);

            return Json(Math.Round(finalCpuCounter,2).ToString() + "%", JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 4
0
		static Func<ulong> GetElapsedTimeSampler(PerformanceCounter pc) {
			var scale = 1.0 / 1000;
			return () => {
				var sample = pc.NextSample();
				return (ulong)((sample.CounterTimeStamp - sample.RawValue) / (scale * sample.CounterFrequency));
			};
		}
Exemplo n.º 5
0
 private static long WaitForNextRawValue(PerformanceCounter counter)
 {
     long used;
     while((used = counter.NextSample().RawValue) == 0)
     {
         Thread.Sleep(10);
     }
     return used;
 }
    private string _name; // The name of the adapter.

    #endregion

    #region Private methods

    /// <summary>
    /// Instances of this class are supposed to be created only in an NetworkMonitorHandler.
    /// </summary>
    internal NetworkAdapter(string name)
    {
      _name = name;

      // Create performance counters for the adapter.
      _dlCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", this._name);
      _ulCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", this._name);

      // Since dlValueOld and ulValueOld are used in method update() to calculate network speed,
      // they must have be initialized.
      _dlValueOld = _dlCounter.NextSample().RawValue;
      _ulValueOld = _ulCounter.NextSample().RawValue;
    }
Exemplo n.º 7
0
        public Dictionary<string, float> GetCpusUsage()
        {
            performanceCounter = new PerformanceCounter("Processor Information", "% Processor Time");
            var counterCategory = new PerformanceCounterCategory("Processor Information");
            var instances = counterCategory.GetInstanceNames();
            var samples = instances.ToDictionary(x=>x,y=>new List<CounterSample>());

            for (int i = 0; i < 2; i++)
            {
                foreach (var instanceName in instances)
                {
                    performanceCounter.InstanceName = instanceName;
                    samples[instanceName].Add(performanceCounter.NextSample());
                    Thread.Sleep(100);
                }
            }
            return samples.ToDictionary(x => x.Key, y => Calculate(y.Value[0], y.Value[1]));
        }
Exemplo n.º 8
0
        public DiskActivity(int interval = 1000)
        {
            _performanceCounter = new PerformanceCounter("PhysicalDisk", "% Idle Time");
            var performanceCounterCategory = new PerformanceCounterCategory("PhysicalDisk");
            _instances = performanceCounterCategory.GetInstanceNames();
            _counterSamples = new Dictionary<string, CounterSample>();

            foreach (var s in _instances)
            {
                _performanceCounter.InstanceName = s;
                _counterSamples.Add(s, _performanceCounter.NextSample());
            }

            _updateTimer = new Timer
            {
                AutoReset = true,
                Interval = interval
            };

            _updateTimer.Elapsed += UpdateTimerOnElapsed;

            _updateTimer.Start();
        }
Exemplo n.º 9
0
        public CpuLoad(int interval = 1000)
        {
            _performanceCounter = new PerformanceCounter("Processor Information", "% Processor Time");
            var performanceCounterCategory = new PerformanceCounterCategory("Processor Information");
            _instances = performanceCounterCategory.GetInstanceNames();
            _counterSamples = new Dictionary<string, CounterSample>();

            foreach (var s in _instances)
            {
                _performanceCounter.InstanceName = s;
                _counterSamples.Add(s, _performanceCounter.NextSample());
            }

            _updateTimer = new Timer
            {
                AutoReset = true,
                Interval = interval
            };

            _updateTimer.Elapsed += UpdateTimerOnElapsed;

            _updateTimer.Start();
        }
Exemplo n.º 10
0
		public static long? SafelyGetPerformanceCounter(string categoryName, string counterName, string processName)
		{
			try
			{
				if (PerformanceCounterCategory.Exists(categoryName) == false)
					return null;
				var category = new PerformanceCounterCategory(categoryName);
				var instances = category.GetInstanceNames();
				var ravenInstance = instances.FirstOrDefault(x => x == processName);
				if (ravenInstance == null || !category.CounterExists(counterName))
				{
					return null;
				}
				using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true))
				{
					return counter.NextSample().RawValue;
				}
			}
			catch (Exception e)
			{
				//Don't log anything here, it's up to the calling code to decide what to do
				return null;
			}
		}
        static void Main(string[] args)
        {
            // Getting Hostname.
            var Hostname = System.Environment.MachineName;

            // Making sure that the command is being run with Argument Values.
            if (args.Length == 0)
            {
                Console.WriteLine("A [Processor_Instance], [Warning Percent] and a [Critical Percent] Value must be provided!");
                Environment.Exit(3);
            }

            try
            {

                // Declared Argument Values for Disk, Warning Threshold and Critical Threshold.
                String Arg_0 = args[0];
                String Arg_1 = args[1];
                String Arg_2 = args[2];

                // Testing Argument Variables to determine if they are the correct type of value.
                Match ProcessorInstanceCheck = Regex.Match(Arg_0, @"[A-Z]", RegexOptions.IgnoreCase);
                Match WarningCheck           = Regex.Match(Arg_1, @"[A-Z]", RegexOptions.IgnoreCase);
                Match CriticalCheck          = Regex.Match(Arg_2, @"[A-Z]", RegexOptions.IgnoreCase);

                // Making sure that the Warning Percent Decimal Value is a number.
                if (ProcessorInstanceCheck.Success)
                {
                    Console.WriteLine("A [Proceesor_Instance] Numeric Value (0,1,2,5 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Decimal Value is a number.
                if (WarningCheck.Success)
                {
                    Console.WriteLine("A [Warning Percent] Decimal Value (1.00, 12.00, 90.00 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Making sure that the Critical Percent Decimal Value is a number.
                if (CriticalCheck.Success)
                {
                    Console.WriteLine("A [Critical Percent] Decimal Value (1.00, 12.00, 90.00 etc...) must be provided!");
                    Environment.Exit(3);
                }

                // Converting all Passed Arguments into a Usable State.
                var Warning      = (Convert.ToDouble(args[1]));
                var Critical     = (Convert.ToDouble(args[2]));

                // Making sure that the Warning Percent and Critical Percent Values are not greater than 100%
                if ((Warning > 100.00) || (Critical > 100.00))
                {
                    Console.WriteLine("The [Warning Percent] and [Critical Percent] Values cannot be greater than 100.00!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Value is Less than the Critical Percent Value.
                if (Warning > Critical)
                {
                    Console.WriteLine("The [Warning Percent] Value must be Less than the [Critical Percent] Value!");
                    Environment.Exit(3);
                }

                // Making sure that the Warning Percent Value is not equal to the Critical Percent Value.
                else if (Warning == Critical)
                {
                    Console.WriteLine("The [Warning Percent] Value cannot be Equal to the [Critical Percent] Value!");
                    Environment.Exit(3);
                }

                // Checking to see if the Processor Instance exists.
                if (!System.Diagnostics.PerformanceCounterCategory.InstanceExists(args[0], "Processor"))
                {
                    Console.WriteLine("Processor Instance [{0}] does not exist on {1}!", args[0], Hostname);
                    Environment.Exit(3);
                }

                // Processor Instance is queried.
                var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", args[0], true);

                // Calculating the % Processor Time of the chosen Processor Instance.
                var Sample_1 = cpuCounter.NextSample(); System.Threading.Thread.Sleep(1000);
                var Sample_2 = cpuCounter.NextSample();

                var ProcessorTime = ((1 - ((double)(Sample_2.RawValue - Sample_1.RawValue) / (double)(Sample_2.TimeStamp100nSec - Sample_1.TimeStamp100nSec))) * 100);

                // Final Results and Performance Data are Returned.
                if (ProcessorTime > Critical)
                {
                    Console.WriteLine("[{0}]: % Processor Time = {1}% - CRITICAL | '[{0}]'={1}%;{2};{3};0.00;100.00;", args[0], ProcessorTime.ToString("0.00"), Warning.ToString("0.00"), Critical.ToString("0.00"));
                    Environment.Exit(2);
                }

                else if ((ProcessorTime < Critical) && (ProcessorTime > Warning))
                {
                    Console.WriteLine("[{0}]: % Processor Time = {1}% - WARNING | '[{0}]'={1}%;{2};{3};0.00;100.00;", args[0], ProcessorTime.ToString("0.00"), Warning.ToString("0.00"), Critical.ToString("0.00"));
                    Environment.Exit(1);
                }

                else if (ProcessorTime < Warning)
                {
                    Console.WriteLine("[{0}]: % Processor Time = {1}% - OK | '[{0}]'={1}%;{2};{3};0.00;100.00;", args[0], ProcessorTime.ToString("0.00"), Warning.ToString("0.00"), Critical.ToString("0.00"));
                    Environment.Exit(0);
                }
            }

            //// Catching Exception Errors here due to Missing Variables or Syntax Issues.
            catch (Exception Error)
            {
                if (Error is IndexOutOfRangeException)
                {
                    Console.WriteLine("The [Warning Percent] and [Critical Percent] Variables must BOTH be present!");
                    Environment.Exit(3);
                }

                else if (Error is FormatException)
                {
                    Console.WriteLine("Please check the format of the values you have assigned to your variables.");
                    Environment.Exit(3);
                }

            }
        }
Exemplo n.º 12
0
 public static CounterSample GetPerformanceCounterSample(string categoryName,
                                                         string instanceName,
                                                         string counterName)
 {
     using (PerformanceCounter counter = new PerformanceCounter())
     {
         counter.CategoryName = categoryName;
         counter.CounterName = counterName;
         counter.InstanceName = instanceName;
         return counter.NextSample();
     }
 }
Exemplo n.º 13
0
 private void LogPerformanceCounterData(PerformanceCounter memoryMonitor, PerformanceCounter processorMonitor)
 {
     LogMessage(string.Format("\t\tMemory Usage:\t{0,15:N0}", memoryMonitor.NextSample().RawValue));
     LogMessage(string.Format("\t\tProcessor Usage:{0,15:N0}", processorMonitor.NextSample().RawValue));
 }
Exemplo n.º 14
0
        } // MonitorInventory(Object context, BackgroundWorker worker, int refreshMS, int singulationLimit, int readerCycleLimit)

        /// <summary>
        /// Read Tag memory
        /// </summary>
        /// <param name="context"></param>
        /// <param name="worker"></param>
        /// <param name="refreshMS"></param>
        /// <returns></returns>
        //public ReportBase TagAccess(Object context, BackgroundWorker worker, int refreshMS, int r_iTagAccessReqCount)//??把计??//Add LargeRead command
        public ReportBase TagAccess(Object context, BackgroundWorker worker, int refreshMS, int r_iTagAccessReqCount, int r_iTagAccessReqCountRead)//??把计??//Add LargeRead command
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine( String.Format( "{0}() ThreadID = {1}", System.Reflection.MethodInfo.GetCurrentMethod( ).Name, Thread.CurrentThread.ManagedThreadId ) );
#endif
            if ( IsDisposed )
                throw new ObjectDisposedException( "LakeChabotReader" );

            if ( Mode != rfidReader.OperationMode.BoundToReader )
                return new rfidSimpleReport( context, OperationOutcome.FailByContext,
                    new rfidException( rfidErrorCode.ReaderIsNotBound, "Reader must be bound before tag can be read." ) );

            if ( _control.State != FunctionControl.FunctionState.Idle )
                return new rfidSimpleReport( context, OperationOutcome.FailByContext, new Exception( "Cannot read the tag, the prior task has not completed" ) );

            if ( null == worker )
                return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ArgumentNullException( "worker", "BackgroundWorker is required" ) );

            if ( refreshMS < MIN_REFRESH_MS || refreshMS > MAX_REFRESH_MS )
                return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ArgumentOutOfRangeException( "refreshMS", refreshMS, string.Format( "Value must be between {0} and {1}", MIN_REFRESH_MS, MAX_REFRESH_MS ) ) );

            // Tag Read is never in continuous mode
            rfid.Constants.RadioOperationMode priorMode = ReaderOperationMode;
            if ( priorMode != rfid.Constants.RadioOperationMode.NONCONTINUOUS )
            {
                ReaderOperationMode = rfid.Constants.RadioOperationMode.NONCONTINUOUS;
            }

            _refreshRateMS = refreshMS;
            _bgdWorker = worker;
            _requestTagList.Clear( );
            _periodTagList.Clear( );
#pragma warning disable 420 // reference to a volatile field is valid for Interlocked call
            System.Threading.Interlocked.Exchange( ref _commonAccessCount, 0 );
#pragma warning restore 420
            rfidOperationReport report  = new rfidOperationReport( context,
                                                                   ElapsedMilliseconds,
                                                                   RequestCount,
                                                                   RawAntennaCycleCount,
                                                                   RawInventoryCycleCount,
                                                                   BadPacketCount,
                                                                   CRCErrorCount,
                                                                   RawPacketCount,
                                                                   RawRoundCount,
                                                                   RawInventoryCount,
                                                                   SessionUniqueTags,
                                                                   RequestUniqueTags,
                                                                   CurrentUniqueTags,
                                                                   SessionDuration );

            _control.StartAction( );

            //_managedAccess.Callback = PacketCallBackFromReader;

            PerformanceCounter processorUtilizationCounter = null;

            try
            {
                processorUtilizationCounter = new PerformanceCounter( "Processor", "% Processor Time", "_Total", "." );
            }
            catch ( Exception ) { }

            //ReaderInterfaceThreadClass threadClass = new ReaderInterfaceThreadClass(_managedAccess, (int)ReaderHandle, TagAccessDataSet);//??把计??//Add LargeRead command
            ReaderInterfaceThreadClass threadClass = new ReaderInterfaceThreadClass(_managedAccess, (int)ReaderHandle, TagAccessDataSet, TagAccessReadSet);//??把计??//Add LargeRead command
            threadClass._reader = this; // HACK
            Thread runnerThread = new Thread(new ThreadStart(threadClass.AccessThreadProc));
            runnerThread.Name = "AccessTag";
            runnerThread.IsBackground = true;
            runnerThread.Priority = ThreadPriority.BelowNormal;
            runnerThread.Start( );

            int notused = FileHandler.TotalPacketCount; // Make sure the file is created;

            // Wait for thread to be in ready state
            int counter = 500;
            while ( counter-- > 0 && ( int ) ( runnerThread.ThreadState & System.Threading.ThreadState.WaitSleepJoin ) == 1 )
            {
                Thread.Sleep( 10 );
            }
            if ( !runnerThread.IsAlive )
            {
                return new rfidSimpleReport( context, OperationOutcome.FailByApplicationError, new ApplicationException( "BackgroundWorker thread could not be started." ) );
            }

            ReaderRequest readerRequest = new ReaderRequest( );
            readerRequest.reader = _theReaderID.Name;
#pragma warning disable 420 // reference to a volatile field is valid for Interlocked call
            readerRequest.requestSequence = System.Threading.Interlocked.Increment( ref _commonRequestIndex );
#pragma warning restore 420
            readerRequest.requestName = rfidReader.GetNameForRequest( rfidReader.ReaderRequestType.TagAccess );
            readerRequest.startTime = GetSessionRelativeDateTime( report.StartTimeMS );
            readerRequest.requestStartTime = report.StartTimeMS;
            readerRequest.startingPacketCount = RawPacketCount;
            readerRequest.startingTagCount = RawInventoryCount;

            MemoryStream data = new MemoryStream( );
            readerRequest.WriteTo( data );
            PacketData.PacketWrapper pseudoPacket = new PacketData.PacketWrapper( new PacketData.CommandPsuedoPacket( readerRequest.requestName, data.ToArray( ) ), PacketData.PacketType.U_N_D_F_I_N_E_D );
            pseudoPacket.IsPseudoPacket = true;
            pseudoPacket.ReaderName = _theReaderID.Name;
            pseudoPacket.ReaderIndex = ( int ) _theReaderID.Handle;
            FileHandler.WritePacket( pseudoPacket );

            //clark 2011.2.18 Record that user request data length
            TagAccessReqCount = r_iTagAccessReqCount;
            TagAccessReqCountRead = r_iTagAccessReqCountRead;//把计??

            DateTime ReportDue = DateTime.Now.AddMilliseconds( refreshMS );
            threadClass.StartEvent.Set( );

            while ( runnerThread.IsAlive )
            {
                CounterSample sample = CounterSample.Empty;
                if ( processorUtilizationCounter != null )
                {
                    try
                    {
                        sample = processorUtilizationCounter.NextSample( );
                    }
                    catch ( Exception ) { }
                }
                ProcessQueuedPackets( );

                QueueEvent.WaitOne( 30, true );
                QueueEvent.Reset( );

                DateTime now = DateTime.Now;

                if ( ReportDue.Ticks <= now.Ticks )
                {
                    //Debug.WriteLine(String.Format("Reporing Progress Now (Elapsed Milliseconds {0})", ElapsedMilliseconds));
                    _bgdWorker.ReportProgress(
                        0,
                        report.GetProgressReport( ElapsedMilliseconds,
                                                  RequestCount,
                                                  RawAntennaCycleCount,
                                                  RawInventoryCycleCount,
                                                  BadPacketCount,
                                                  CRCErrorCount,
                                                  RawPacketCount,
                                                  RawRoundCount,
                                                  RawInventoryCount,
                                                  SessionUniqueTags,
                                                  RequestUniqueTags,
                                                  CurrentUniqueTags,
                                                  SessionDuration ) );
                    _periodTagList.Clear( );
                    ReportDue = now.AddMilliseconds( refreshMS );
                }

                if ( !runnerThread.IsAlive )
                    break;

                if ( FunctionController.GetActionRequest( ) == FunctionControl.RequestedAction.Abort )
                {
                    threadClass.Stop = true;
                    Result abortError = Result.OK;
                    try
                    {
                        abortError = LakeChabotReader.MANAGED_ACCESS.API_ControlAbort();
                    }
                    catch ( Exception e )
                    {
                        Debug.WriteLine( String.Format( "Error attempting to abort: {0}", e.Message ) );
                    }
                    break;
                }

                if ( FunctionController.GetActionRequest( ) == FunctionControl.RequestedAction.Stop )
                {
                    threadClass.Stop = true;
                    Result stopError = Result.OK;
                    try
                    {
                        stopError = LakeChabotReader.MANAGED_ACCESS.API_ControlCancel();
                    }
                    catch ( Exception e )
                    {
                        Debug.WriteLine( String.Format( "Error attempting to stop: {0}", e.Message ) );
                    }
                    if ( Result.OK != stopError )
                    {
                        // Try to abort
                    }
                    break;
                }

                if ( FunctionController.State == FunctionControl.FunctionState.Paused )
                {
                    do
                    {
                        Thread.Sleep( refreshMS );
                    } while ( FunctionController.State == FunctionControl.FunctionState.Paused );
                }

                if ( !runnerThread.IsAlive )
                    break;

                float processorUtilization = 0;
                if ( processorUtilizationCounter != null && sample != CounterSample.Empty )
                {
                    try
                    {
                        CounterSample.Calculate( sample, processorUtilizationCounter.NextSample( ) );
                    }
                    catch ( Exception ) { }
                }
                // Debug.WriteLine(String.Format("Processor Util: {0}", processorUtilization));

                if ( processorUtilization > ( float ) TARGET_MAX_USAGE_PERCENT )
                    _packetSleepMS += SLEEP_ADD_SUBTRACT_MS;
                else
                    _packetSleepMS -= _packetSleepMS <= MIN_SLEEP_TIME_MS ? 0 : SLEEP_ADD_SUBTRACT_MS;
            }

            runnerThread.Join( );

            // Get any leftover packets
            ProcessQueuedPackets( );

            if ( LastCommandResult != 0 ) MacClearError( );

            OperationOutcome outcome = OperationOutcome.Success;
            string result = threadClass.Result;
            if ( !( result == null || result == "" || result == "OK" ) )
            {
                switch ( _control.State )
                {
                    case FunctionControl.FunctionState.Stopping:
                        outcome = OperationOutcome.SuccessWithUserCancel;
                        break;

                    case FunctionControl.FunctionState.Aborting:
                        outcome = OperationOutcome.FailByUserAbort;
                        break;

                    // case FunctionControl.FunctionState.Running:
                    //     outcome = OperationOutcome.FailByReaderError;
                    //     report.ErrorMessage = result;
                    //     break;

                    case FunctionControl.FunctionState.Idle:
                    case FunctionControl.FunctionState.Paused:
                    case FunctionControl.FunctionState.Unknown:
                    default:
                        outcome = OperationOutcome.Unknown;
                        break;
                }
            }

            _control.Finished( );

            report.OperationCompleted( outcome,
                                       ElapsedMilliseconds,
                                       RequestCount,
                                       RawAntennaCycleCount,
                                       RawInventoryCycleCount,
                                       BadPacketCount,
                                       CRCErrorCount,
                                       RawPacketCount,
                                       RawRoundCount,
                                       RawInventoryCount,
                                       SessionUniqueTags,
                                       RequestUniqueTags,
                                       CurrentUniqueTags,
                                       SessionDuration );

            // reset the mode
            ReaderOperationMode = priorMode;

            if ( EnableLogging )
            {
                //Push data from buffer to file. And clear buffer.
                PacketLogger.Flush(); 
            }

            return report;
        }
Exemplo n.º 15
0
        private void DoLoop()
        {
            _conn = new UdpClient(_options.PhoneIp, _options.PhonePort);

            var ramFreeCounter = new PerformanceCounter("Memory", "Available MBytes");
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var totalRam = computerInfo.TotalPhysicalMemory / 1024 / 1024;

            CreateNetworkCounters();

            var pc = new PerformanceCounter("Processor", "% Processor Time");
            var instances = new PerformanceCounterCategory("Processor").GetInstanceNames();
            var cs = new Dictionary<string, CounterSample>();

            foreach (var s in instances)
            {
                pc.InstanceName = s;
                cs.Add(s, pc.NextSample());
            }
            Thread.Sleep(999);

            var drives = DriveInfo.GetDrives();

            var volume = new Volume();

            _getIpsBw.DoWork += GetIps;
            //_getIpsBw.RunWorkerAsync(true);

            var myipTimer = new Timer(StartBw, null, TimeSpan.Zero, TimeSpan.FromMinutes(_options.MyipInterval));

            while (_continue)
            {
                var startTime = DateTime.Now;

                var strout = ".start.";
                foreach (var s in instances)
                {
                    pc.InstanceName = s;
                    var ns = pc.NextSample();
                    if (s.Equals("_Total")) strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 2) + "\n";
                    else strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 0) + "\n";
                    cs[s] = ns;
                }
                strout += "MemUsed|" + (totalRam - ramFreeCounter.NextValue()) + "\n";
                strout += "MemTotal|" + totalRam + "\n";

                try
                {
                    strout += "NetIn|" + networkInCounter.NextValue() + "\n";
                    strout += "NetOut|" + networkOutCounter.NextValue() + "\n";
                }
                catch (Exception e)
                {
                    _mainForm.LogLine("Warning: Failed to get network activity: " + e);
                    _mainForm.LogLine("Resetting to first adapter.");
                    _options.NetIndex = 0;
                    CreateNetworkCounters();
                }
                strout += "LocalIp|" + _localIp + "\n";
                strout += "RemoteIp|" + _remoteIp + "\n";

                if (RescanDrives)
                {
                    _mainForm.LogLine("Drivechange detected, rescanning drives.", true);
                    drives = DriveInfo.GetDrives();
                    RescanDrives = false;
                }
                foreach (var drive in drives.Where(drive => drive.DriveType == DriveType.Fixed))
                {
                    try
                    {
                        strout += "DriveInfo|" + drive.Name + "|" + drive.AvailableFreeSpace + "\n";
                    }
                    catch
                    {

                    }
                }

                strout += "Np|" + GetNp() + "\n";

                var muteStatus = volume.GetMute();
                var vol = volume.GetVol();

                strout += "mute|" + (muteStatus ? "1" : "0") + "\n";
                strout += "vol|" + vol + "\n";

                SendInfo(strout);

                var duration = DateTime.Now - startTime;
                if (duration.Milliseconds > 1000)
                {
                    _mainForm.LogLine("Warning: Iterating took " + duration.Milliseconds + "ms, should be less than 1s.");
                }
                else _mainForm.LogLine("Iterating took " + duration.Milliseconds + "ms", true);
                Thread.Sleep(1000 - duration.Milliseconds);
            }

            ramFreeCounter.Close();
            pc.Close();
            myipTimer.Dispose();
            volume.Dispose();
        }
        //private static float GetPerformanceCounterValueByInstanceDeux(string perfCategory, string perfCounterName, string perfInstanceName, out string PerfCounterType, int sleep = 50)
        //{
        //    pCounter = new PerformanceCounter();
        //    PerfCounterType = "";
        //    try
        //    {
        //        pCounter.CategoryName = perfCategory;
        //        pCounter.CounterName = perfCounterName;
        //        pCounter.InstanceName = perfInstanceName;
        //        try
        //        {
        //            pCounter.NextValue();
        //            pFirstSample = pCounter.NextSample();
        //            Thread.Sleep(sleep);
        //            float nv = pCounter.NextValue();
        //            pSecondSample = pCounter.NextSample();
        //            float avg = CounterSample.Calculate(pFirstSample, pSecondSample);
        //            Console.WriteLine("{0}, {1}", nv, avg);
        //            return avg;
        //        }
        //        finally
        //        {
        //            pCounter.Dispose();
        //        }
        //    }
        //    catch
        //    {
        //        try
        //        {
        //            PerformanceCounter pc = new PerformanceCounter(LookupPerfNameByName(perfCategory), LookupPerfNameByName(perfCounterName), perfInstanceName);
        //            pc.NextValue();
        //            Thread.Sleep(sleep);
        //            try
        //            {
        //                PerfCounterType = pc.CounterType.ToString();
        //                return pc.NextValue();
        //            }
        //            finally
        //            {
        //                pc.Dispose();
        //            }
        //        }
        //        catch
        //        {
        //            // I give up, didnt manage to figure out the correct name for the PerformanceCounter.
        //            Console.WriteLine("ERROR: Error looking up PerformanceCounter '" + perfCategory + "\\" + perfCounterName + "' for " + perfInstanceName + "'");
        //            return -1;
        //        }
        //    }
        //}
        public static string GetPerformanceCounterValueAsString(string perfCategory, string perfCounterName, out string PerfCounterType, int sleep = 50)
        {
            //float badresult = -1;
            try
            {
                PerformanceCounter pc = new PerformanceCounter(perfCategory, perfCounterName);
                pc.NextValue();
                Console.WriteLine(pc.NextSample());
                Thread.Sleep(sleep);
                try
                {
                    PerfCounterType = pc.CounterType.ToString();
                    return pc.NextValue().ToString("0.0");
                }
                finally
                {
                    pc.Dispose();
                }

                //return pc.RawValue;
            }
            catch
            {
                try
                {
                    PerformanceCounter pc = new PerformanceCounter(LookupPerfNameByName(perfCategory), LookupPerfNameByName(perfCounterName));
                    pc.NextValue();
                    Thread.Sleep(sleep);

                    try {
                        PerfCounterType = pc.CounterType.ToString();
                        return pc.NextValue().ToString("0.0");
                    }
                    finally
                    {
                        pc.Dispose();
                    }
                }
                catch
                {
                    // I give up, didnt manage to figure out the correct name for the PerformanceCounter.
                    Console.WriteLine("ERROR: Error looking up PerformanceCounter '" + perfCategory + "\\" + perfCounterName + "'");
                    PerfCounterType = "missing";
                    return "missing";
                }
            }
        }
        public IPerformanceCounter LoadCounter(string categoryName, string counterName, string instanceName, bool isReadOnly)
        {
            // See http://msdn.microsoft.com/en-us/library/356cx381.aspx for the list of exceptions
            // and when they are thrown. 
            try
            {
                var counter = new PerformanceCounter(categoryName, counterName, instanceName, isReadOnly);

                // Initialize the counter sample
                counter.NextSample();

                return new PerformanceCounterWrapper(counter);
            }
#if UTILS
            catch (InvalidOperationException) { return null; }
            catch (UnauthorizedAccessException) { return null; }
            catch (Win32Exception) { return null; }
            catch (PlatformNotSupportedException) { return null; }
#else
            catch (InvalidOperationException ex)
            {
                _trace.TraceEvent(TraceEventType.Error, 0, "Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (UnauthorizedAccessException ex)
            {
                _trace.TraceEvent(TraceEventType.Error, 0, "Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (Win32Exception ex)
            {
                _trace.TraceEvent(TraceEventType.Error, 0, "Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (PlatformNotSupportedException ex)
            {
                _trace.TraceEvent(TraceEventType.Error, 0, "Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
#endif
        }
Exemplo n.º 18
0
        internal int Run()
        {
            string thisProcessName = Process.GetCurrentProcess().ProcessName;
            using (PerformanceCounter memoryMonitor = new PerformanceCounter("Process", "Working Set", thisProcessName))
            {
                memoryMonitor.NextSample();
                using (PerformanceCounter processorMonitor = new PerformanceCounter("Process", "% Processor Time", thisProcessName))
                {
                    processorMonitor.NextSample();
                    networkGeneratorLog = new List<string>();
                    LogMessage("********************************************************");
                    LogMessage(string.Format("{0,25}\t{1:G}", "Start Network Generation:", DateTime.Now));
                    LogMessage(string.Format("{0,25}\t{1:N0}\tEdges: {2:N0}", "Requested Nodes:", this.networkNodeCount, this.networkEdgeCount));
                    LogMessage(string.Format("{0,25}\t{1:N0}\tEdges: {2:N0}", "Start Ids - Nodes:", this.nodeIdStartValue, this.edgeIDStartValue));
                    ChirperGraphMLDocument graphDoc = new ChirperGraphMLDocument();
                    LogMessage(string.Empty);
                    LogMessage("Starting node generation...");

                    TimeSpan nodeGenerationTime = GenerateChirperUserNodes(graphDoc);
                    LogMessage("\tNode generation complete in " + nodeGenerationTime);
                    LogPerformanceCounterData(memoryMonitor, processorMonitor);

                    LogMessage(string.Empty);
                    FlushLog();

                    int duplicateEdgeStatistic = 0;
                    TimeSpan edgeGenerationTime = default(TimeSpan);
                    if (this.networkEdgeCount > 0)
                    {
                        LogMessage("Starting edge generation...");
                        edgeGenerationTime = GenerateChirperFollowerEdge(graphDoc, ref duplicateEdgeStatistic);

                        LogMessage("\tEdge generation complete in " + edgeGenerationTime);
                        LogMessage("\tDuplicates generated: " + duplicateEdgeStatistic);
                        LogPerformanceCounterData(memoryMonitor, processorMonitor);
                        LogMessage(string.Empty);
                    }
                    else
                    {
                        LogMessage("Edge generation suppressed from command line.");
                        LogMessage(string.Empty);
                    }

                    Stopwatch stopwatch = new Stopwatch();
                    FlushLog();

                    LogMessage("Starting GraphML File write...");
                    stopwatch.Restart();
                    graphDoc.WriteXmlWithWriter(this.graphMLFile);
                    stopwatch.Stop();
                    TimeSpan xmlWriteTime = TimeSpan.FromSeconds(stopwatch.Elapsed.TotalSeconds);
                    LogMessage("\tGraphML file write complete in " + xmlWriteTime);
                    LogPerformanceCounterData(memoryMonitor, processorMonitor);

                    LogMessage(string.Empty);
                    LogMessage(string.Format(CultureInfo.InvariantCulture, "{0,30}\t{1}", "Total Graph Generation Time:", (nodeGenerationTime + edgeGenerationTime + xmlWriteTime)));
                    LogMessage(string.Empty);
                    FlushLog();

                    // Get the size of the file so we can add the statistic.
                    FileInfo fileInfo = new FileInfo(this.graphMLFile);
                    fileInfo.Refresh();
                    long fileLength = fileInfo.Length;
                    string range = "bytes";
                    if (fileLength > Kilo)
                    {
                        fileLength = fileLength / Kilo;
                        range = "KB";
                    }
                    if (fileLength > Kilo)
                    {
                        fileLength = fileLength / Kilo;
                        range = "MB";
                    }

                    LogMessage(string.Format(CultureInfo.InvariantCulture, "{0,30}\t{1:N0} {2}", "GraphML File Size:", fileLength, range));

                    LogMessage(string.Empty);
                    FlushLog();

                }
            }

            // Using Linq to XML here to insert the statistic comment won't adversely affect performance.
            //XComment statisticsComment = new XComment(summaryMessageStringBuilder.ToString());
            //XDocument generatedGraphMLDoc = XDocument.Load(graphMLFile);
            //XElement graphElement = generatedGraphMLDoc.Root;
            //graphElement.AddFirst(statisticsComment);
            //graphElement.Document.Save(this.graphMLFile);

            return 0;
        }
 private static PerformanceCounter LoadCounter(string category, string name, string host, string instance = null)
 {
     try
     {
         var counter = new PerformanceCounter(category, name, instance, host);
         counter.NextSample();
         return counter;
     }
     catch (Exception)
     {
         Console.WriteLine("Unable to load counter '{0}\\{1}' on host '{2}'", category, name, host);
         return null;
     }
 }
Exemplo n.º 20
0
 private static void LoadCounter(string category, string name, string instance, string machine = "localhost")
 {
     try
     {
         var counter = new PerformanceCounter(category, name, instance, machine);
         _samples[counter] = new List<CounterSample> { counter.NextSample() };
         _counters.Add(counter);
     }
     catch (Exception)
     {
         Console.WriteLine("Failed to load counter '{0}\\{1}({2})' for machine '{3}'", category, name, instance, machine);
     }
 }
Exemplo n.º 21
-1
        static void CollectingMemory()
        {
            Process currentProcess = Process.GetCurrentProcess();
            var privateByteCounter = new PerformanceCounter("Process", "Working Set - Private", currentProcess.ProcessName);
            var netMemoryCounter = new PerformanceCounter(".NET CLR Memory", "# Bytes in all Heaps", currentProcess.ProcessName);

            while (!done)
            {
                maxNetMemory = Math.Max(netMemoryCounter.NextSample().RawValue / 1024, maxNetMemory);
                maxPrivateWorkingSet = Math.Max(privateByteCounter.NextSample().RawValue / 1024, maxPrivateWorkingSet);
                Thread.Sleep(100);
            }

            privateByteCounter.Dispose();
            netMemoryCounter.Dispose();
        }