/// <summary> /// Return Download Speed in MBs /// </summary> /// <param name="lInstance">Network Interface ID</param> /// <param name="lDelay">Delay in seconds for more precision</param> /// <returns></returns> public static float GetDownloadSpeed(int lInstance = 1, int lDelay = 1) { PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string networkInstance = performanceCounterCategory.GetInstanceNames()[lInstance]; PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInstance); performanceCounterReceived.NextValue(); Thread.Sleep(lDelay * 1000); float downloadSpeed = performanceCounterReceived.NextValue() / (1024f * 1024f); return downloadSpeed; }
private void toolStripButton1_Click(object sender, EventArgs e) { if (running == false) { running = true; chart.Series[0].Points.Clear(); chart.Series[1].Points.Clear(); int network_interface_index = -1; PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string[] adapters = performanceCounterCategory.GetInstanceNames(); for (int i = 0; i < adapters.Length; i++) { if (adapters[i] == interface_label.Text) { network_interface_index = i; } } if (network_interface_index != -1) { string instance = performanceCounterCategory.GetInstanceNames()[network_interface_index]; PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); Stopwatch stopWatch = new Stopwatch(); stopWatch.Reset(); stopWatch.Start(); aTimer = new System.Timers.Timer(); aTimer.Interval = (int)(float.Parse(refresh_rate_textbox.Text) * 1000); aTimer.Elapsed += delegate { OnTimedEvent(network_interface_index, performanceCounterSent, performanceCounterReceived, stopWatch); }; aTimer.AutoReset = true; aTimer.Enabled = true; } } }
public void ToolLoad() { if (Properties.Settings.Default.FirstRun) { Properties.Settings.Default.FirstRun = false; Properties.Settings.Default.Adapter = PCC.GetInstanceNames()[0]; Properties.Settings.Default.Left = Top; Properties.Settings.Default.Top = Left; Properties.Settings.Default.Save(); } else { Top = Properties.Settings.Default.Top; Left = Properties.Settings.Default.Left; } LocalAdapter = Properties.Settings.Default.Adapter; Topmost = true; foreach (var item in PCC.GetInstanceNames()) { MenuItem menuItem = new MenuItem { Header = item }; menuItem.Click += Set_Instance; if (LocalAdapter == item) { menuItem.IsChecked = true; } Adapter.Items.Add(menuItem); } using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { if (key.GetValueNames().Contains("Net Speed")) { AutoStart.IsChecked = true; } else { AutoStart.IsChecked = false; } } tokenSource = new CancellationTokenSource(); token = tokenSource.Token; Worker = new Task(() => Get_Speed(), token); Worker.RunSynchronously(); }
/// <summary> /// Re-creates the _counters list if the number /// of valid PerformanceCounters has changed. /// </summary> private void RefreshCounters() { PerformanceCounterCategory cat = new PerformanceCounterCategory("Network Interface"); if (cat.GetInstanceNames().Length != _counters.Count) { _counters.Clear(); foreach (string instance in cat.GetInstanceNames()) { _counters.Add(new PerformanceCounter("Network Interface", _counterName, instance)); } } }
private static string[] GetInstances(string _Category, string _SqlInstance) { List <string> instances = new List <string>(); PerformanceCounterCategory category = new PerformanceCounterCategory(_Category, _SqlInstance); if (category.GetInstanceNames() != null) { foreach (string instance in category.GetInstanceNames()) { instances.Add(instance); } } return(instances.ToArray()); }
private void SaveNetworkBandwidth() { string[] arrInstanceNames; dtNI.Rows.Clear(); try { PerformanceCounterCategory pcCat = new PerformanceCounterCategory(); if (PerformanceCounterCategory.Exists("Network Interface")) { pcCat.CategoryName = "Network Interface"; arrInstanceNames = pcCat.GetInstanceNames(); foreach (string strInterface in arrInstanceNames) { PerformanceCounter PC = new PerformanceCounter(); PC.CategoryName = "Network Interface"; PC.CounterName = "Current bandwidth"; PC.InstanceName = strInterface; PC.NextValue(); System.Threading.Thread.Sleep(50); dtNI.Rows.Add(strInterface, PC.NextValue()); } } } catch (Exception ex) { WSPEvent.WriteEvent(ex.Message, "E", 1110); } }
private void Initialize() { if (_initialized) { return; } var category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0"); var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", _processId))); if (!instanceNames.Any()) { return; } _bytesSent = new PerformanceCounter { CategoryName = ".NET CLR Networking 4.0.0.0", CounterName = "Bytes Sent", InstanceName = instanceNames.First(), ReadOnly = true }; _bytesReceived = new PerformanceCounter { CategoryName = ".NET CLR Networking 4.0.0.0", CounterName = "Bytes Received", InstanceName = instanceNames.First(), ReadOnly = true }; _initialized = true; }
private static void EnumerateCountersFor(string category) { var sb = new StringBuilder(); var counterCategory = new PerformanceCounterCategory(category); if (counterCategory.CategoryType == PerformanceCounterCategoryType.SingleInstance) { foreach (var counter in counterCategory.GetCounters()) { sb.AppendLine(string.Format("{0}:{1}", category, counter.CounterName)); } } else { foreach (var counterInstance in counterCategory.GetInstanceNames()) { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } } Console.WriteLine(sb.ToString()); }
public static void GetInstanceNameListANDCounterNameList(string CategoryName) { string[] instanceNames; ArrayList counters = new ArrayList(); PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName); try { instanceNames = mycat.GetInstanceNames(); if (instanceNames.Length == 0) { counters.AddRange(mycat.GetCounters()); } else { for (int i = 0; i < instanceNames.Length; i++) { counters.AddRange(mycat.GetCounters(instanceNames[i])); } } for (int i = 0; i < instanceNames.Length; i++) { Console.WriteLine(instanceNames[i]); } Console.WriteLine("******************************"); foreach (PerformanceCounter counter in counters) { Console.WriteLine(counter.CounterName); } } catch (Exception) { Console.WriteLine("Unable to list the counters for this category"); } }
public Form1() { cpu = new CPU(); ram = new RAM(); disk = new Disk(); PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface"); foreach (string name in category.GetInstanceNames()) { if (name == "MS TCP Loopback interface") { continue; } // 这可不是个好方法 if (name == "Intel[R] Dual Band Wireless-AC 3168") { network = new Network(name); } Network n = new Network(name); if (n.isConnect) { network = n; break; } } InitializeComponent(); }
private static void EnumerateCounters() { var categories = PerformanceCounterCategory.GetCategories().Select(c => c.CategoryName).OrderBy(s => s).ToArray(); var sb = new StringBuilder(); foreach (var category in categories) { var counterCategory = new PerformanceCounterCategory(category); foreach (var counterInstance in counterCategory.GetInstanceNames()) { try { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } catch { // Drop it on the floor } } } Console.WriteLine(sb.ToString()); }
private static Dictionary <uint, string> MatchProcessPidsWithCounterInstances(string categoryName, string counterName) { var pids = new Dictionary <uint, string>(); // pid <-> instance name var perfcat = new PerformanceCounterCategory(categoryName); string[] instances = perfcat.GetInstanceNames(); // now for each instance let's figure out its pid foreach (var inst in instances) { try { using (var counter = new PerformanceCounter(categoryName, counterName, inst, true)) { var ppid = (uint)counter.NextValue(); // _Total and Idle have PID = 0 - we don't need them if (ppid > 0 && !pids.ContainsKey(ppid)) { pids.Add(ppid, inst); logger.Debug("Matched PID: {0} with instance: {1} ({2})", ppid, inst, categoryName); } } } catch (InvalidOperationException ex) { logger.Warn(string.Format("Performance counter '{0}' didn't send any value.", inst), ex); } } return(pids); }
public Monitor() { cpu = new Cpu(); cpu.StartUpdate(); ram = new Ram(); ram.StartUpdate(); List <string> NetsList = new List <string>(); PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface"); foreach (string name in category.GetInstanceNames()) { if (name == "MS TCP Loopback interface" || name == "Teredo Tunneling Pseudo-Interface") { continue; } Network n = new Network(name); if (n.isConnect) { NetsList.Add(name); } } Nets = NetsList.ToArray(); if (Nets.Length >= 1) { StartMonitorNetwork(Nets[0]); } }
private void LoadNetworkCardName() { try { PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface"); string[] instancename = category.GetInstanceNames(); while (string.IsNullOrEmpty(networkCardName)) { foreach (string name in instancename) { double utilization = GetNetworkUtilization(name.TrimStart().TrimEnd()); if (utilization != 0) { networkCardName = name; networkCardLabel.Invoke((MethodInvoker) delegate { networkCardLabel.Text = networkCardName; }); break; } } } } catch (Exception ex) { Util.LogToFile(ex.ToString()); } }
/// <summary> /// If having multiple instances with the same process-name, then they will get different instance names /// </summary> private static string GetCurrentProcessInstanceName(string category) { try { using (Process proc = Process.GetCurrentProcess()) { int pid = proc.Id; PerformanceCounterCategory cat = new PerformanceCounterCategory(category); foreach (string instanceValue in cat.GetInstanceNames()) { using (PerformanceCounter cnt = new PerformanceCounter(category, "ID Process", instanceValue, true)) { int val = (int)cnt.RawValue; if (val == pid) { return(instanceValue); } } } InternalLogger.Debug("PerformanceCounter - Failed to auto detect current process instance. ProcessId={0}", pid); } } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } InternalLogger.Warn(ex, "PerformanceCounter - Failed to auto detect current process instance."); } return(string.Empty); }
public string GetBandwithUsage() { var performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); var instance = performanceCounterCategory.GetInstanceNames()[1]; var totalUsedBandwith = new PerformanceCounter("Network Interface", "Bytes Total/sec", instance); var maxAvailableBandwidth = new PerformanceCounter("Network Interface", "Current Bandwidth", instance); var used = totalUsedBandwith.NextValue(); var total = maxAvailableBandwidth.NextValue(); for (int i = 0; i < 10; i++) { used += totalUsedBandwith.NextValue(); Thread.Sleep(100); } used = used / 10; var value = (int)(used * 100 / total); if (value > 100) { value = 100; } else if (value < 0) { value = 0; } return(value.ToString()); }
private void TryToInitializeCounters() { if (!countersInitialized) { PerformanceCounterCategory category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0"); var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", pid))); if (instanceNames.Any()) { bytesSentPerformanceCounter = new PerformanceCounter(); bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesSentPerformanceCounter.CounterName = "Bytes Sent"; bytesSentPerformanceCounter.InstanceName = instanceNames.First(); bytesSentPerformanceCounter.ReadOnly = true; bytesReceivedPerformanceCounter = new PerformanceCounter(); bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesReceivedPerformanceCounter.CounterName = "Bytes Received"; bytesReceivedPerformanceCounter.InstanceName = instanceNames.First(); bytesReceivedPerformanceCounter.ReadOnly = true; countersInitialized = true; } } }
//Given a process id, get the specific instance name it is ties to public static string GetInstanceNameForProcessId(int processId) { string[] instances = null; var process = Process.GetProcessById(processId); string processName = Path.GetFileNameWithoutExtension(process.ProcessName); PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); instances = cat.GetInstanceNames().Where(inst => inst.StartsWith(processName)).ToArray(); foreach (string instance in instances) { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true)) { int val = (int)cnt.RawValue; if (val == processId) { return(instance); } } } return(null); }
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); } }
public static bool TryGetInstanceName(Process process, out string instanceName) { try { PerformanceCounterCategory processCategory = new PerformanceCounterCategory(CategoryName); string[] instanceNames = processCategory.GetInstanceNames(); foreach (string name in instanceNames) { if (name.StartsWith(process.ProcessName)) { using ( PerformanceCounter processIdCounter = new PerformanceCounter(CategoryName, ProcessIdCounter, name, true)) { if (process.Id == (int)processIdCounter.RawValue) { instanceName = name; return(true); } } } } instanceName = null; return(false); } catch { instanceName = null; return(false); } }
public static List <string> GetPerformableDiskInstanceNames(bool ignoreDriveType = false) { try { if (PerformanceCounterCategory.Exists("PhysicalDisk")) { List <string> instanceNames = new List <string>(); PerformanceCounterCategory category = new PerformanceCounterCategory("PhysicalDisk"); foreach (string instanceName in category.GetInstanceNames()) { if (instanceName.LastIndexOf(':') == -1) { continue; } string[] logicalDrives = Regex.Replace(instanceName, @"\d\s", "").Split(' '); DriveInfo driveInfo = new DriveInfo(Regex.Replace(logicalDrives[0], ":", "")); if (ignoreDriveType || !ignoreDriveType && driveInfo.DriveType == DriveType.Fixed) { instanceNames.Add(instanceName); } } return(instanceNames); } } catch { throw; } return(null); }
public long GetDatabaseTransactionVersionSizeInBytes() { try { const string categoryName = "Database ==> Instances"; if (PerformanceCounterCategory.Exists(categoryName) == false) { return(-1); } var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var ravenInstance = instances.FirstOrDefault(x => x.StartsWith(uniqueRrefix)); const string counterName = "Version Buckets Allocated"; if (ravenInstance == null || !category.CounterExists(counterName)) { return(-2); } using (var counter = new PerformanceCounter(categoryName, counterName, ravenInstance, readOnly: true)) { var value = counter.NextValue(); return((long)(value * TransactionalStorageConfigurator.GetVersionPageSize())); } } catch (Exception e) { if (reportedGetDatabaseTransactionCacheSizeInBytesError == false) { reportedGetDatabaseTransactionCacheSizeInBytesError = true; log.WarnException("Failed to get Version Buckets Allocated value, this error will only be reported once.", e); } return(-3); } }
private static void PerformanceCounterInitOnece() { if (!_isPerformanceCounterInited) { lock (_lockForPerformanceCounter) { if (!_isPerformanceCounterInited) { string processInstanceName = _appProcess.ProcessName; PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); // 同一个程序如果运行多次,对应的多个进程名称是通过后缀#1、#2、#3...区分的 string[] instanceNames = cat.GetInstanceNames().Where(a => a.StartsWith(_appProcess.ProcessName)).ToArray(); foreach (string instanceName in instanceNames) { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instanceName, true)) { int val = (int)cnt.RawValue; if (val == _appProcess.Id) { processInstanceName = instanceName; break; } } } _memoryCounter = new PerformanceCounter("Process", "Working Set - Private", processInstanceName, readOnly: true); _threadCounter = new PerformanceCounter("Process", "Thread Count", processInstanceName, readOnly: true); _handleCounter = new PerformanceCounter("Process", "Handle Count", processInstanceName, readOnly: true); _isPerformanceCounterInited = true; } } } }
private static bool WaitForInstance(string categoryName, string instanceId) { LogHelper.Log("Waiting for counter set instance {0}", instanceId); var category = new PerformanceCounterCategory(categoryName); int count = 0; while (count < 20) { count++; try { if (category.GetInstanceNames().Where(i => string.Compare(i, instanceId) == 0).Any()) { LogHelper.Log("Counter set instance {0} found", instanceId); return(true); } } catch (InvalidOperationException e) { LogHelper.Log("Exception {0}. Closing the performance counter resources will cause it to reinitialize.", e); PerformanceCounter.CloseSharedResources(); } Thread.Sleep(500); } LogHelper.Log("Counter set instance {0} not found", instanceId); return(false); }
private void RefreshDriveList() { comboBox1.Items.Clear(); /* * foreach (string logicalDrive in Environment.GetLogicalDrives) * { * DriveInfo driveInfo = new DriveInfo(logicalDrive); * if (driveInfo.IsReady) * { * this.comboBox1.Items.Add((object)(logicalDrive.ToUpper() + " [" + driveInfo.DriveFormat.ToString() + "]"));//; " + (object)(driveInfo.TotalSize / 1024L / 1024L) + " / " + (object)(driveInfo.AvailableFreeSpace / 1024L / 1024L) + " MiB]")); * } * } */ /* * foreach (System.IO.DriveInfo drive in System.IO.DriveInfo.GetDrives()) * { * if (drive.DriveType == System.IO.DriveType.Fixed) * { * comboBox1.Items.Add(drive.Name.ToString()); * } * } */ PerformanceCounterCategory pfcCat = new PerformanceCounterCategory("PhysicalDisk"); comboBox1.Items.AddRange(pfcCat.GetInstanceNames()); }
private void TrackContextSwitches() { PerformanceCounterCategory allThreadsWithPerformanceCounters = new PerformanceCounterCategory("Thread"); PerformanceCounter[] performanceCountersForThisThread = null; // Iterate over all "Thread" category performance counters on system (includes numerous processes) foreach (string threadName in allThreadsWithPerformanceCounters.GetInstanceNames()) { // Obtain those performance counters for the OrleansHost if (threadName.Contains("OrleansHost") && threadName.EndsWith("/" + Thread.CurrentThread.ManagedThreadId)) { performanceCountersForThisThread = allThreadsWithPerformanceCounters.GetCounters(threadName); break; } } // In the case that the performance was not obtained correctly (this condition is null), we simply will not have stats for context switches if (performanceCountersForThisThread == null) { return; } // Look at all performance counters for this thread foreach (PerformanceCounter performanceCounter in performanceCountersForThisThread) { // Find performance counter for context switches if (performanceCounter.CounterName == CONTEXT_SWTICH_COUNTER_NAME) { // Use raw value for logging, should show total context switches FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_CONTEXT_SWITCHES, Name), () => (float)performanceCounter.RawValue, CounterStorage.LogOnly); } } }
private void InitializeNetworkCounters() { //create a performance counter group for these guys m_NetworkCounters = new PerfCounterCollection("Network Counters", "System-wide network performance counters (not specific to the process being monitored)"); //register our favorite performance counters with the monitoring system try { //add in a monitor for each network interface PerformanceCounterCategory networkCounters = new PerformanceCounterCategory("Network Interface"); string[] networkInterfaceNames = networkCounters.GetInstanceNames(); foreach (string interfaceName in networkInterfaceNames) { //eliminate the loopback interface, we never care about that. if (interfaceName != "MS TCP Loopback interface" && interfaceName != "lo") { m_NetworkCounters.Add("Network Interface", "Bytes Received/sec", interfaceName); m_NetworkCounters.Add("Network Interface", "Bytes Sent/sec", interfaceName); m_NetworkCounters.Add("Network Interface", "Current Bandwidth", interfaceName); m_NetworkCounters.Add("Network Interface", "Packets Received Errors", interfaceName); m_NetworkCounters.Add("Network Interface", "Packets Outbound Errors", interfaceName); } } } catch (Exception exception) { GC.KeepAlive(exception); //some warning prevention... Log.Write(LogMessageSeverity.Warning, LogWriteMode.Queued, exception, "Gibraltar.Agent", "Unable to record performance information for network counters", "Specific exception: {0}\r\nException message: {1}", exception.GetType().FullName, exception.Message); } }
/// <summary> /// 根据PID获取InstanceName(不要用于性能计数器,#1..实例名会自动改变) /// </summary> /// <param name="id"></param> /// <returns></returns> public static string GetInstanceNameById(int id) { try { PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); string[] instances = cat.GetInstanceNames(); foreach (string instance in instances) { try { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true)) { int val = (int)cnt.RawValue; if (val == id) { return(instance); } } } catch { } } } catch { } return(null); }
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) { //Don't log anything here, it's up to the calling code to decide what to do return(null); } }
public static string FindInstanceName(string categoryName) { var result = String.Empty; thisProc = Process.GetCurrentProcess(); if (!ReferenceEquals(thisProc, null)) { if (!String.IsNullOrEmpty(categoryName)) { if (CheckForPerformanceCounterCategoryExist(categoryName)) { var category = new PerformanceCounterCategory(categoryName); var instances = category.GetInstanceNames(); var processName = thisProc.ProcessName; if (instances != null) { foreach (var instance in instances) { if (instance.ToLower().Equals(processName.ToLower())) { result = instance; break; } } } } } } return(result); }
/// <summary> /// Get the specific Windows instance name for a program /// </summary> /// <param name="processId">Process ID</param> /// <returns>Instance name if found, otherwise an empty string</returns> /// <remarks>If multiple programs named Chrome.exe are running, the first is Chrome.exe, the second is Chrome.exe#1, etc.</remarks> public string GetInstanceNameForProcessId(int processId) { try { var runningProcess = Process.GetProcessById(processId); var processName = Path.GetFileNameWithoutExtension(runningProcess.ProcessName); var processCategory = new PerformanceCounterCategory("Process"); var perfCounterInstances = (from item in processCategory.GetInstanceNames() where item.StartsWith(processName) select item).ToList(); foreach (var instanceName in perfCounterInstances) { using (var counterInstance = new PerformanceCounter("Process", "ID Process", instanceName, true)) { var instanceProcessID = Convert.ToInt32(counterInstance.RawValue); if (instanceProcessID == processId) { return(instanceName); } } } } catch (Exception) { return(string.Empty); } return(string.Empty); }
//public static string GetProcessPriority() //{ // string priopity = string.Empty; // ConnectionOptions co = new ConnectionOptions { Username = null }; // ManagementScope ms = new ManagementScope("\\\\" + Logic.ServerName + "\\root\\CIMV2", co); // ObjectQuery q = new ObjectQuery("Select * from Win32_Process"); // ManagementObjectSearcher os = new ManagementObjectSearcher(ms, q); // ManagementObjectCollection moc = os.Get(); // foreach (ManagementBaseObject o in moc) // { // } // return priopity; //} /// <summary> /// Получение имя инстанса исследуемого процесса /// </summary> /// <param name="process">Исследуемый процесс</param> /// <returns></returns> public static string InstanceName(this Process process) { int pid = process.Id; string name = process.ProcessName; string server = process.MachineName; PerformanceCounterCategory cat = new PerformanceCounterCategory("Process", server); List <string> instances = cat.GetInstanceNames().Where(inst => inst.StartsWith(name)).ToList(); foreach (string instance in instances) { using (PerformanceCounter pc = new PerformanceCounter("Process", "ID Process", instance, server)) { try { int val = (int)pc.RawValue; if (val == pid) { return(instance); } } catch { //ignored } } } throw new Exception( $"Could not find performance counter instance name for process '{name}'. This is truly strange ..."); }
public static void mesure_init_2(List<String> names) { PlugwiseLib.BLL.BC.PlugwiseDeviceInfo calib; string fileName = @"C:\GreenCodeLab_Plugwyse\log.txt"; TextWriter writer; writer = new StreamWriter(fileName); string entete = ""; int num = 0; for (int i = 0; i < 9; i++) { if (Plug_act[i] == true) { calib = control.InitPlug(TimerMesure.Plug_mac[i],serialPort); if (calib != null) { Plug_Ok[i] = true; Plug_Calib[i] = calib; if (bufferisation == false) { entete = entete + names[i] + ";%CPU " + (i + 1).ToString() + ";Bytes/S " + (i + 1).ToString() + ";Disk Bytes/S " + (i + 1).ToString() + ";consommation " + (i + 1).ToString() + ";Impact consommation " + (i + 1).ToString(); } else { entete = entete + names[i] + ";"; } Array.Resize(ref Plug_num, num + 1); Plug_num[num] = i; num++; } else { Plug_Ok[i] = false; } } else { Plug_Ok[i] = false; } } writer.WriteLine(entete); writer.Close(); if (mesurecpu == true) { PerformanceCounterCategory networkCategory; string instanceName = null; PCounter = new PerformanceCounter(); PCounter.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter.CategoryName = "Processor"; PCounter.CounterName = "% Processor Time"; PCounter.InstanceName = "_Total"; PCounter2 = new PerformanceCounter(); PCounter2.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter2.CategoryName = "Network Interface"; PCounter2.CounterName = "Bytes Total/sec"; networkCategory = new PerformanceCounterCategory("Network Interface"); foreach (string instance in networkCategory.GetInstanceNames()) { Console.WriteLine(instance); if (instance == "Realtek PCIe FE Family Controller") { instanceName = instance; break; } } PCounter2.InstanceName = instanceName; PCounter3 = new PerformanceCounter(); PCounter3.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter3.CategoryName = "PhysicalDisk"; PCounter3.CounterName = "% Disk Time"; PCounter3.InstanceName = "_Total"; } }
private static void EnumerateCountersFor(string category) { var sb = new StringBuilder(); var counterCategory = new PerformanceCounterCategory(category); if(counterCategory.CategoryType == PerformanceCounterCategoryType.SingleInstance) { foreach (var counter in counterCategory.GetCounters()) { sb.AppendLine(string.Format("{0}:{1}", category, counter.CounterName)); } } else { foreach (var counterInstance in counterCategory.GetInstanceNames()) { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } } Console.WriteLine(sb.ToString()); }
private static void EnumerateCounters() { var categories = PerformanceCounterCategory.GetCategories().Select(c => c.CategoryName).OrderBy(s => s).ToArray(); var sb = new StringBuilder(); foreach (var category in categories) { var counterCategory = new PerformanceCounterCategory(category); foreach (var counterInstance in counterCategory.GetInstanceNames()) { try { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } catch { // Drop it on the floor } } } Console.WriteLine(sb.ToString()); }