• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Diagnostics.PerformanceCounterCategory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Diagnostics.PerformanceCounterCategory的典型用法代码示例。如果您正苦于以下问题:C# PerformanceCounterCategory类的具体用法?C# PerformanceCounterCategory怎么用?C# PerformanceCounterCategory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



PerformanceCounterCategory类属于System.Diagnostics命名空间,在下文中一共展示了PerformanceCounterCategory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetOrCreateCounterCategory

        /// <summary>
        /// Gets the or create counter category.
        /// </summary>
        /// <param name="categoryInfo">The category information.</param>
        /// <param name="counters">The counters.</param>
        /// <returns>PerformanceCounterCategory.</returns>
        private static PerformanceCounterCategory GetOrCreateCounterCategory(
            PerformanceCounterCategoryInfo categoryInfo, CounterCreationData[] counters)
        {
            var creationPending = true;
            var categoryExists = false;
            var categoryName = categoryInfo.CategoryName;
            var counterNames = new HashSet<string>(counters.Select(info => info.CounterName));
            PerformanceCounterCategory category = null;

            if (PerformanceCounterCategory.Exists(categoryName))
            {
                categoryExists = true;
                category = new PerformanceCounterCategory(categoryName);
                var counterList = category.GetCounters();
                if (category.CategoryType == categoryInfo.CategoryType && counterList.Length == counterNames.Count)
                {
                    creationPending = counterList.Any(x => !counterNames.Contains(x.CounterName));
                }
            }

            if (!creationPending) return category;

            if (categoryExists)
                PerformanceCounterCategory.Delete(categoryName);

            var counterCollection = new CounterCreationDataCollection(counters);

            category = PerformanceCounterCategory.Create(
                categoryInfo.CategoryName,
                categoryInfo.CategoryHelp,
                categoryInfo.CategoryType,
                counterCollection);

            return category;
        }
开发者ID:bradsjm,项目名称:DotEmwin,代码行数:41,代码来源:PerformanceCounterManager.cs


示例2: WatchCpuAndMemory

        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);
            }
        }
开发者ID:LeeWangyeol,项目名称:Scut,代码行数:30,代码来源:UtilsTest.cs


示例3: GetInstances

        public IEnumerable<string> GetInstances(string category)
        {
            var counterCategory = new PerformanceCounterCategory(category);
            var instances = counterCategory.GetInstanceNames();

            return instances;
        }
开发者ID:paybyphone,项目名称:spectator,代码行数:7,代码来源:PerformanceCounterCategoryRepository.cs


示例4: Enabling_performance_counters_should_result_in_performance_counters_being_created

        public void Enabling_performance_counters_should_result_in_performance_counters_being_created()
        {
            //This will delete an recreate the categories.
            PerformanceCategoryCreator.CreateCategories();

            var outboundIntances = new PerformanceCounterCategory(OutboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            var inboundIntances = new PerformanceCounterCategory(InboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            Assert.Empty(outboundIntances);
            Assert.Empty(inboundIntances);

            var hostConfiguration = new RhinoQueuesHostConfiguration()
                .EnablePerformanceCounters()
                .Bus("rhino.queues://localhost/test_queue2", "test");

            container = new WindsorContainer();
            new RhinoServiceBusConfiguration()
                .UseConfiguration(hostConfiguration.ToBusConfiguration())
                .UseCastleWindsor(container)
                .Configure();
            bus = container.Resolve<IStartableServiceBus>();
            bus.Start();

            using (var tx = new TransactionScope())
            {
                bus.Send(bus.Endpoint, "test message.");
                tx.Complete();
            }

            outboundIntances = new PerformanceCounterCategory(OutboundPerfomanceCounters.CATEGORY).GetInstanceNames();
            inboundIntances = new PerformanceCounterCategory(InboundPerfomanceCounters.CATEGORY).GetInstanceNames();

            Assert.NotEmpty(outboundIntances.Where(name => name.Contains("test_queue2")));
            Assert.NotEmpty(inboundIntances.Where(name => name.Contains("test_queue2")));
        }
开发者ID:mtscout6,项目名称:rhino-esb,代码行数:34,代码来源:EnablingRhinoQueuesPerformanceCounters.cs


示例5: TryToInitializeCounters

        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;
                }
            }
        }
开发者ID:hendrikdelarey,项目名称:appcampus,代码行数:26,代码来源:NetworkTrafficUtilities.cs


示例6: TryGetInstanceName

        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;
            }
        }
开发者ID:RedpointGames,项目名称:Protogame,代码行数:32,代码来源:GCMetricsProfilerVisualiser.cs


示例7: EnumerateCountersFor

        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());
        }
开发者ID:VS1URL,项目名称:metrics-net,代码行数:25,代码来源:CLRProfilerTests.cs


示例8: OptionsFormVisibleChanged

        private void OptionsFormVisibleChanged(object sender, EventArgs e)
        {
            if (Visible == false)
            {
                return;
            }

            textBoxPhoneIp.Text = _options.PhoneIp;
            textBoxPhonePort.Text = _options.PhonePort.ToString();
            textBoxMyipHost.Text = _options.MyipHost;
            textBoxMyipPort.Text = _options.MyipPort.ToString();
            textBoxMyipUrl.Text = _options.MyipUrl;
            textBoxMyipInterval.Text = _options.MyipInterval.ToString();
            textBoxNpFile.Text = _options.NpFile;
            checkBoxSendNp.Checked = _options.SendNp;

            // set listBoxNetworkInterface
            listBoxNetworkInterface.Items.Clear();
            var instanceNames = new PerformanceCounterCategory("Network Interface").GetInstanceNames();
            listBoxNetworkInterface.Items.AddRange(instanceNames);
            if (instanceNames.Length > 0)
            {
                listBoxNetworkInterface.SelectedIndex = 0;
            }
            if (instanceNames.Length > _options.NetIndex)
            {
                listBoxNetworkInterface.SelectedIndex = _options.NetIndex;
            }
        }
开发者ID:Logima,项目名称:vinfo-server,代码行数:29,代码来源:OptionsForm.cs


示例9: SetVariables

 private static void SetVariables(int eth = 0)
 {
     performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
     instance = performanceCounterCategory.GetInstanceNames()[eth]; // 1st NIC !
     performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
     performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);
 }
开发者ID:ccasalicchio,项目名称:Portable-Asp.net-Web-Server,代码行数:7,代码来源:HttpMon.cs


示例10: Configure

        public void Configure()
        {
            var counters = CounterList;

            counters.Add("Processor Load", "Processor", "% Processor Time", "_Total");
            counters.Add("Memory Usage", "Memory", "% Committed Bytes In Use");

            counters.Add("IIS Requests/sec", "Web Service", "Total Method Requests/sec", "_Total");
            //this one is very unreliable
            counters.Add("ASP.NET Request/Sec", "ASP.NET Applications", "Requests/Sec", "__Total__");

            counters.Add("ASP.NET Current Requests", "ASP.NET", "Requests Current");
            counters.Add("ASP.NET Queued Requests", "ASP.NET", "Requests Queued");
            counters.Add("ASP.NET Requests Wait Time", "ASP.NET", "Request Wait Time");

            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
            String[] instanceNames = category.GetInstanceNames();

            foreach (string name in instanceNames)
            {
                counters.Add("Net IO Total: " + name, "Network Interface", "Bytes Total/sec", name);
                counters.Add("Net IO Received: " + name, "Network Interface", "Bytes Received/sec", name);
                counters.Add("Net IO Sent: " + name, "Network Interface", "Bytes Sent/sec", name);
            }
        }
开发者ID:RickStrahl,项目名称:WestWindWebSurge,代码行数:25,代码来源:PerformanceStats.cs


示例11: PerfCounters

		static PerfCounters()
		{
			var p = Process.GetCurrentProcess();
			ProcessName = p.ProcessName;
			ProcessId = p.Id;

			CategoryProcess = new PerformanceCounterCategory("Process");

			ProcessorTime = new PerformanceCounter("Process", "% Processor Time", ProcessName);
			UserTime = new PerformanceCounter("Process", "% User Time", ProcessName);

			PrivateBytes = new PerformanceCounter("Process", "Private Bytes", ProcessName);
			VirtualBytes = new PerformanceCounter("Process", "Virtual Bytes", ProcessName);
			VirtualBytesPeak = new PerformanceCounter("Process", "Virtual Bytes Peak", ProcessName);
			WorkingSet = new PerformanceCounter("Process", "Working Set", ProcessName);
			WorkingSetPeak = new PerformanceCounter("Process", "Working Set Peak", ProcessName);
			HandleCount = new PerformanceCounter("Process", "Handle Count", ProcessName);

			CategoryNetClrMemory = new PerformanceCounterCategory(".NET CLR Memory");
			ClrBytesInAllHeaps = new PerformanceCounter(".NET CLR Memory", "# Bytes in all Heaps", ProcessName);
			ClrTimeInGC = new PerformanceCounter(".NET CLR Memory", "% Time in GC", ProcessName);
			ClrGen0Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 0 Collections", p.ProcessName, true);
			ClrGen1Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections", p.ProcessName, true);
			ClrGen2Collections = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections", p.ProcessName, true);
		}
开发者ID:Rustemt,项目名称:foundationdb-dotnet-client,代码行数:25,代码来源:PerfCounters.cs


示例12: GetStandardValues

		/// <summary>
		/// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
		/// </summary>
		/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context that can be used to extract additional information about the environment from which this converter is invoked. This parameter or properties of this parameter can be null.</param>
		/// <returns>
		/// A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> that holds a standard set of valid values, or null if the data type does not support a standard set of values.
		/// </returns>
		public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
		{
			INuGenCounter counter = (context == null) ? null : (context.Instance as INuGenCounter);

			string machineName = ".";
			string categoryName = string.Empty;

			if (counter != null)
			{
				machineName = counter.MachineName;
				categoryName = counter.CategoryName;
			}

			try
			{
				PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName);
				string[] instances = category.GetInstanceNames();
				Array.Sort(instances, Comparer.Default);
				return new TypeConverter.StandardValuesCollection(instances);
			}
			catch
			{
			}

			return null;
		}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:33,代码来源:NuGenInstanceNameConverter.cs


示例13: Initialize

        public static void Initialize()
        {
            if (Log.IsInfoEnabled)
            {
                Log.InfoFormat("Start to initialize {0} performance counters", CategoryName);
            }

            if (!IsUserAdmin())
            {
                Log.Info("User has no Admin rights. CustomAuthResultCounters initialization skipped");
                return;
            }

            try
            {
                PerformanceCounterCategory = GetOrCreateCategory(CategoryName, GetCounterCreationData());
            }
            catch (Exception e)
            {
                Log.WarnFormat("Exception happened during counters initialization. Excpetion {0}", e);
                return;
            }

            if (Log.IsInfoEnabled)
            {
                Log.InfoFormat("{0} performance counters successfully initialized", CategoryName);
            }
        }
开发者ID:JerryBian,项目名称:PhotonSample,代码行数:28,代码来源:CustomAuthResultCounters.cs


示例14: PerfCounterMBean

 public PerfCounterMBean(string perfObjectName, string perfInstanceName, IEnumerable<string> perfCounterNames, bool useProcessInstanceName, bool useAllCounters)
 {
     _perfObjectName = perfObjectName;
      if (useProcessInstanceName)
      {
     Process p = Process.GetCurrentProcess();
     _perfInstanceName = p.ProcessName;
      }
      else
      {
     _perfInstanceName = perfInstanceName ?? "";
      }
      _category = new PerformanceCounterCategory(_perfObjectName);
      if (useAllCounters)
      {
     foreach (PerformanceCounter counter in _category.GetCounters(_perfInstanceName))
     {
        _counters[counter.CounterName] = counter;
     }
      }
      else if (perfCounterNames != null)
      {
     foreach (string counterName in perfCounterNames)
     {
        PerformanceCounter counter;
        counter = new PerformanceCounter(_perfObjectName, counterName, _perfInstanceName, true);
        _counters.Add(counterName, counter);
     }
      }
 }
开发者ID:SzymonPobiega,项目名称:NetMX,代码行数:30,代码来源:PerfCounterMBean.cs


示例15: NetworkIO

        public NetworkIO()
        {
            _dict = new Dictionary<string, double>();
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");

            var interfaces = GetNetworkInterfaces();
            var categoryList = category.GetInstanceNames();

            foreach (string name in categoryList)
            {
                var nicName = name.Replace('[', '(').Replace(']', ')');
                if (!interfaces.Select(t => t.Description).Contains(nicName) || nicName.ToLower().Contains("loopback"))
                    continue;
                try
                {
                    NetworkAdapter adapter = new NetworkAdapter(interfaces.First(t => t.Description.Contains(nicName)).Name);
                    adapter.NetworkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
                    adapter.NetworkBytesSend = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
                    _adappterList.Add(adapter);         // Add it to ArrayList adapter
                }
                catch
                {
                    //pass
                }
            }
        }
开发者ID:chinaboard,项目名称:PureCat,代码行数:26,代码来源:NetworkIO.cs


示例16: GetPerformanceCounterCategories

        public static List<PerformanceCounterCategoryModel> GetPerformanceCounterCategories()
        {
            var counterCategories = new List<PerformanceCounterCategoryModel>();

            PerformanceCounterCategory.GetCategories().ToList().ForEach((i) =>
                counterCategories.Add(new PerformanceCounterCategoryModel { Name = i.CategoryName })
                );

            counterCategories = counterCategories.OrderBy(x => x.Name).ToList();

            counterCategories.ForEach((i) => {
                try {
                    var cat = new PerformanceCounterCategory(i.Name);
                    var instances = cat.GetInstanceNames();

                    if(instances.Length > 0) {
                        foreach(var instance in instances) {
                            i.Instances.Add(instance);
                        }
                    }
                }
                catch {
                    // sometimes this freaks out when an instance can't be examined
                }
            });

            return counterCategories;
        }
开发者ID:AndyCross,项目名称:CloudMonitR,代码行数:28,代码来源:PerformanceCounterFactory.cs


示例17: LogicalDisk

        // Try to discover GUID from buggy Performance Monitor instance names.
        // Note: Discover drive GUID comparing free space is uggly, but MS gave me no choice.
        static LogicalDisk()
        {
            // =====         WMI         =====
            Win32_Volume[] vols = Win32_Volume.GetAllVolumes();
            // Free megabytes and volume GUID relation
            Dictionary<ulong, Guid> wmiFree = new Dictionary<ulong, Guid>(vols.Length);
            // Volume name and volume GUID relation
            Dictionary<string, Guid> wmiName = new Dictionary<string, Guid>(vols.Length);

            foreach (Win32_Volume v in vols) {
                if (v.Automount &&
                    v.DriveType == System.IO.DriveType.Fixed) {
                    if (v.IsMounted) {
                        wmiName.Add(v.Name.TrimEnd('\\'), v.DeviceGuid);
                    } else {
                        wmiFree.Add(v.FreeSpace / MB_MULT, v.DeviceGuid);
                    }
                }
            }
            perfMonGuid = new Dictionary<Guid, string>(wmiFree.Count + wmiName.Count);

            // ===== PERFORMANCE MONITOR ======
            PerformanceCounterCategory perfCat = new PerformanceCounterCategory(
                Localization.GetName(COUNTER_LOGICAL_DISK));
            // TODO: Find a faster way to get instance names.
            string[] instances = perfCat.GetInstanceNames();
            // Free megabytes and Performance Monitor instance name
            Dictionary<ulong, string> perfFree = new Dictionary<ulong, string>(instances.Length);

            foreach (string item in instances) {
                if (item == "_Total")
                    continue;

                Guid volId = Guid.Empty;
                if (wmiName.TryGetValue(item, out volId)) {
                    perfMonGuid.Add(volId, item);
                } else {
                    PerformanceCounter p = new PerformanceCounter(
                        Localization.GetName(COUNTER_LOGICAL_DISK),
                        Localization.GetName(COUNTER_FREE_MB),
                        item);
                    perfFree.Add((ulong)p.RawValue, item);
                    p.Close();
                    p.Dispose();
                }
            }

            ulong[] warray = new ulong[wmiFree.Count];
            ulong[] pmarray = new ulong[perfFree.Count];
            if (warray.Length != pmarray.Length)
                throw new NotSupportedException(MSG_EXCEPTION);
            wmiFree.Keys.CopyTo(warray, 0);
            perfFree.Keys.CopyTo(pmarray, 0);
            Array.Sort<ulong>(warray);
            Array.Sort<ulong>(pmarray);

            for (int i = 0; i < warray.Length; i++) {
                perfMonGuid.Add(wmiFree[warray[i]], perfFree[pmarray[i]]);
            }
        }
开发者ID:skarllot,项目名称:zbxlld,代码行数:62,代码来源:LogicalDisk.cs


示例18: GetPerfCounters

 public ICollection GetPerfCounters(string category)
 {
     var r = new ArrayList();
     var cat = new PerformanceCounterCategory(category);
     foreach (var counter in cat.GetCounters()) {
         r.Add(new DictionaryEntry(counter.CounterName, counter.NextValue()));
     }
     return r;
 }
开发者ID:ruanzx,项目名称:mausch,代码行数:9,代码来源:IndexController.cs


示例19: ShouldInstallFirstCategory

        public void ShouldInstallFirstCategory()
        {
            PerformanceCountersInstaller installer = GetCommandLineConfiguredInstaller(firstCategory);
            DoCommitInstall(installer);

            PerformanceCounterCategory category = new PerformanceCounterCategory(firstCategory);

            AssertCategoryIsCorrect(category);
        }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:9,代码来源:PerformanceCountersInstallerFixture.cs


示例20: GetPerformanceCounterCategory

 public static PerformanceCounterCategory GetPerformanceCounterCategory(string category, string machineName)
 {
     PerformanceCounterCategory cat;
     if (string.IsNullOrEmpty(machineName))
         cat = new PerformanceCounterCategory(category);
     else
         cat = new PerformanceCounterCategory(category, machineName);
     return cat;
 }
开发者ID:mb3m,项目名称:Influx-Capacitor,代码行数:9,代码来源:PerformanceCounterHelper.cs



注:本文中的System.Diagnostics.PerformanceCounterCategory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Diagnostics.Process类代码示例发布时间:2022-05-26
下一篇:
C# Diagnostics.PerformanceCounter类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap