/// <summary> /// This method is responsible for monitoring system resource and user activity with the computer /// And periodically changes the shared variable 'crawlerState' /// </summary> public void Scheduler() { PerformanceCounter pc = new PerformanceCounter("Processor", "% Idle Time", "_Total", true); LASTINPUTINFO info = new LASTINPUTINFO(); info.cbSize = Marshal.SizeOf(typeof(LASTINPUTINFO)); while (GlobalData.RunScheduler) { if (GetLastInputInfo(ref info)) { if ((Environment.TickCount - info.dwTime) / 1000 > 5 && (int)pc.NextValue() > 40) { crawlerState = CrawlerState.Run; } else { crawlerState = CrawlerState.Stop; if ((Environment.TickCount - info.dwTime) / 1000 <= 5) GlobalData.lIndexingStatus.Text = string.Format("Indexing is paused and will be resumed in {0} sec of computer inactivity [ CPU Idle : {1:F2}% ]", 5 - (Environment.TickCount - info.dwTime) / 1000, pc.NextValue()); } } Thread.Sleep(1000); } pc.Close(); }
void LogAspThreads() { int availableWorker, availableIO; int maxWorker, maxIO; ThreadPool.GetAvailableThreads(out availableWorker, out availableIO); ThreadPool.GetMaxThreads(out maxWorker, out maxIO); PerformanceCounter c = new PerformanceCounter("Mubble", "Available ASP.NET Worker Threads"); c.ReadOnly = false; c.RawValue = availableWorker; c.Close(); c = new PerformanceCounter("Mubble", "Available ASP.NET IO Threads"); c.ReadOnly = false; c.RawValue = availableIO; c.Close(); c = new PerformanceCounter("Mubble", "Max ASP.NET Worker Threads"); c.ReadOnly = false; c.RawValue = maxWorker; c.Close(); c = new PerformanceCounter("Mubble", "Max ASP.NET IO Threads"); c.ReadOnly = false; c.RawValue = maxIO; c.Close(); }
static void IncrementCounter() { // get an instance of our perf counter PerformanceCounter counter = new PerformanceCounter(); counter.CategoryName = "MyCategory"; counter.CounterName = "AddCounter"; counter.ReadOnly = false; // increment and close the perf counter counter.Increment(); counter.Close(); }
void LogMubbleThreads() { PerformanceCounter c = new PerformanceCounter("Mubble", "Available Mubble Worker Threads"); c.ReadOnly = false; c.RawValue = Worker.MaxThreads - Worker.TotalThreads; c.Close(); c = new PerformanceCounter("Mubble", "Max Mubble Worker Threads"); c.ReadOnly = false; c.RawValue = Worker.MaxThreads; c.Close(); c = new PerformanceCounter("Mubble", "Work items in Mubble queue"); c.ReadOnly = false; c.RawValue = Worker.QueueLength; c.Close(); }
private static void IncrementUnhandledExceptions() { try { string performanceCounterCategory = Assembly.GetEntryAssembly().GetName().Name; string performanceCounterName = "UnhandledExceptions"; PerformanceCounter counter = new PerformanceCounter(); counter.CategoryName = performanceCounterCategory; counter.CounterName = performanceCounterName; counter.ReadOnly = false; counter.Increment(); counter.Close(); } catch (Exception) { return; } }
private static long GetCurrentValue() { try { string performanceCounterCategory = Assembly.GetEntryAssembly().GetName().Name; string performanceCounterName = "UnhandledExceptions"; PerformanceCounter counter = new PerformanceCounter(); counter.CategoryName = performanceCounterCategory; counter.CounterName = performanceCounterName; counter.ReadOnly = true; long current = counter.RawValue; counter.Close(); return current; } catch (Exception ex) { return 0; } }
public void PerformanceCounterTest() { // Delete the Performance Counter Category, if already exists if (PerformanceCounterCategory.Exists("SalesDistribution")) PerformanceCounterCategory.Delete("SalesDistribution"); // Prepare for creation of the Performance Counter CounterCreationDataCollection counterCollection = new CounterCreationDataCollection(); //Create the CounterCreationData CounterCreationData counterData = new CounterCreationData(); counterData.CounterName = "RequestsPerSec"; counterData.CounterType = PerformanceCounterType.NumberOfItems32; counterData.CounterHelp = "Requests Received per Second"; counterCollection.Add(counterData); // Create the performance counter category PerformanceCounterCategory.Create("SalesDistribution", "Automated Sales Distribution System", PerformanceCounterCategoryType.SingleInstance, counterCollection); // Retrieve the performance counter for updation PerformanceCounter performanceCount = new PerformanceCounter("SalesDistribution", "RequestsPerSec", false); int x = 1; while (x <= 50) { Console.WriteLine("RequestsPerSec = {0}", performanceCount.RawValue); // Increment the performance counter performanceCount.Increment(); System.Threading.Thread.Sleep(250); x = (x + 1); } // Close the performance counter performanceCount.Close(); }
private static void OnTimedWpmEvent(Object source, ElapsedEventArgs e) { wpmTimer.Stop(); try { for (var i = 0; i < databases.Count; i++) { SQLiteConnection m_dbConnection = null; bool isToInsert = true; try { int maxAge = 24; String dbPath = databases[i].Split('=')[1]; String testCaseName = databases[i].Split('=')[0]; foreach (String maxAges in databasesMaxAge) { try { String testcaseMaxAgeName = maxAges.Split('=')[0]; int testcaseMaxAgeValue = Convert.ToInt32(maxAges.Split('=')[1]); if (testcaseMaxAgeName == testCaseName) { maxAge = testcaseMaxAgeValue; } } catch { } } m_dbConnection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"); m_dbConnection.Open(); //String dbName = Path.GetFileName(dbPath); //dbName = dbName.Split('.')[0]; //String dbName = databases[i].Split('=')[0]; //check sorting using (SQLiteCommand fmd = m_dbConnection.CreateCommand()) { fmd.CommandText = @"SELECT * FROM sorting ORDER BY start_time DESC LIMIT 1;"; fmd.CommandType = CommandType.Text; SQLiteDataReader r = null; try { r = fmd.ExecuteReader(); } catch { PerformanceCounterCategory.Delete("Alyvix - " + testCaseName); } //r.Read(); List<Performance> perfToQuery = new List<Performance>(); List<Performance> perfToQueryTimedOut = new List<Performance>(); while (r.Read()) { for (int j = 0; j < r.FieldCount; j++) { if (j == 0) continue; try { Performance perf = new Performance(); perf.name = r.GetName(j).Replace("_index", ""); perf.sort = Convert.ToInt32(r[j]); if (perf.sort == -1) perfToQueryTimedOut.Add(perf); else perfToQuery.Add(perf); } catch { } } //String a = Convert.ToString(r["perf_1_index"]); } r.Close(); perfToQuery.Sort(delegate (Performance p1, Performance p2) { return p1.sort.CompareTo(p2.sort); }); List<Performance> SortedList = perfToQuery; SortedList.AddRange(perfToQueryTimedOut); String queryPerfValue = "SELECT start_time"; foreach (Performance perf in SortedList) { queryPerfValue = queryPerfValue + ", " + perf.name; } queryPerfValue = queryPerfValue + " FROM runs ORDER BY start_time DESC LIMIT 1;"; fmd.CommandText = queryPerfValue; fmd.CommandType = CommandType.Text; r = fmd.ExecuteReader(); //r.Read(); List<Performance> perfToSend = new List<Performance>(); CounterCreationDataCollection ccds = new CounterCreationDataCollection(); CounterCreationData counter = new CounterCreationData(); counter.CounterName = "Performance Data"; //perf.name; counter.CounterHelp = "performance Data"; //perf.name; counter.CounterType = PerformanceCounterType.NumberOfItems32; ccds.Add(counter); while (r.Read()) { for (int j = 0; j < r.FieldCount; j++) { if (j == 0) { // Unix timestamp is seconds past epoch DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(Convert.ToDouble(r[j])).ToLocalTime(); DateTime dateNow = DateTime.Now; if (dtDateTime < dateNow.AddHours(-maxAge)) isToInsert = false; continue; //skip start date } try { Performance perf = new Performance(); perf.name = r.GetName(j); try { perf.value = Convert.ToDouble(r[j]); // Convert.ToDouble(1000); //perf.value = Convert.ToInt32(r[j]); } catch { perf.value = -1; } perfToSend.Add(perf); } catch { } } //String a = Convert.ToString(r["perf_1_index"]); } r.Close(); if (isToInsert == false) { try { PerformanceCounterCategory.Delete("Alyvix - " + testCaseName); } catch { } continue; } bool performanceAreTheSame = true; PerformanceCounterCategory existingAlyCat = new PerformanceCounterCategory("Alyvix - " + testCaseName); try { foreach (string perfcount in existingAlyCat.GetInstanceNames()) { bool perfIsPresent = false; foreach (Performance perf in perfToSend) { if (perf.name == perfcount) perfIsPresent = true; } if (perfIsPresent == false) { performanceAreTheSame = false; break; } } if (perfToSend.Count != existingAlyCat.GetInstanceNames().Length) { performanceAreTheSame = false; } } catch { performanceAreTheSame = false; } if (performanceAreTheSame == false) { try { PerformanceCounterCategory.Delete("Alyvix - " + testCaseName); } catch { } } if (!PerformanceCounterCategory.Exists("Alyvix - " + testCaseName)) { try { PerformanceCounterCategory.Create("Alyvix - " + testCaseName, "Alyvix - " + testCaseName, PerformanceCounterCategoryType.MultiInstance, ccds); //System.Threading.Thread.Sleep(1000); } catch (Exception ex) { } } foreach (Performance perf in perfToSend) { PerformanceCounter perfCounter = new PerformanceCounter(); try { perfCounter = new PerformanceCounter("Alyvix - " + testCaseName, "Performance Data", perf.name); perfCounter.ReadOnly = false; perfCounter.RawValue = (long)perf.value; //perfCounter.Increment(); } catch (Exception ex) { } finally { perfCounter.Close(); } } } m_dbConnection.Close(); } catch { } finally { m_dbConnection.Close(); } } } catch { } wpmTimer.Start(); }
private static float GetPerformanceCounterValueByInstance(string perfCategory, string perfCounterName, string perfInstanceName, out string PerfCounterType, int sleep = 50) { PerfCounterType = ""; try { PerformanceCounter pc = new PerformanceCounter(perfCategory, perfCounterName, perfInstanceName); pc.NextValue(); Thread.Sleep(sleep); try { PerfCounterType = pc.CounterType.ToString(); return pc.NextValue(); } finally { pc.Close(); } } catch { try { // Translate the category and countername to CurrentLanguage perfCategory = LookupPerfNameByName(perfCategory); perfCounterName = LookupPerfNameByName(perfCounterName); PerformanceCounter pc = new PerformanceCounter(perfCategory, perfCounterName, perfInstanceName); pc.NextValue(); Thread.Sleep(sleep); try { PerfCounterType = pc.CounterType.ToString(); return pc.NextValue(); } finally { pc.Close(); } } 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; } } }
/// <summary> /// 寫入Waring Log /// </summary> /// <param name="MessageStr">傳入訊息</param> public void WaringLogProcess(string MessageStr) { string URLStr = Request.ServerVariables["URL"].ToString(); string[] WebSite = URLStr.Split('/');//位置2為小模組目錄名稱 XmlDocument xdoc = new XmlDocument(); string LogSettingFilePathAndName = string.Format("{0}/{1}", Application["Config_Path"].ToString(), LogSettingFile ); xdoc.Load(LogSettingFilePathAndName); XmlNodeList RootNodeList = xdoc.SelectNodes("ProcessFile/add"); for (int i = 0; i < RootNodeList.Count; i++) { string ProcessFile = RootNodeList[i].Attributes["File"].Value; SYSModel.LogLevel LogLevelProc = (SYSModel.LogLevel)int.Parse(RootNodeList[i].Attributes["LogLevel"].Value); if (((ProcessFile == "*") && (LogLevelProc >= SYSModel.LogLevel.Waring)) || ((ProcessFile == this.PageCode + ".aspx") && (LogLevelProc >= SYSModel.LogLevel.Waring)) ) { SYSModel.LogHelper ProcLog = new SYSModel.LogHelper(ConnectionDB); ParameterList.Clear(); //Server名稱 ParameterList.Add(Request.ServerVariables["Server_Name"]); //模組名稱 ParameterList.Add(WebSite[2]); //URL ParameterList.Add(Request.Path); //LOGLEVEL ParameterList.Add(SYSModel.LogLevel.Waring); //錯誤訊息 ParameterList.Add(MessageStr); //控制項內容 ParameterList.Add(""); //SQL語法 ParameterList.Add(""); try { //使用者 ParameterList.Add(Session["UID"].ToString()); } catch (Exception ex) { //使用者 ParameterList.Add("SessionUID Timeout"); } PerformanceCounter PC = new PerformanceCounter(); PerformanceCounter PC1 = new PerformanceCounter(); try { //目前記憶體總量 PC.CategoryName = PerformanceCounter_TotalMemoryCategoryName; PC.CounterName = PerformanceCounter_TotalMemoryCounterName; PC.InstanceName = PerformanceCounter_TotalMemoryInstanceName; PC.ReadOnly = true; ParameterList.Add(PC.NextValue()); } catch (Exception ex) { ParameterList.Add(-1); } finally { try { //未釋放的記憶體 PC1.CategoryName = PerformanceCounter_HeapMemoryCategoryName; PC1.CounterName = PerformanceCounter_HeapMemoryCounterName; PC1.InstanceName = PerformanceCounter_HeapMemoryInstanceName; PC1.ReadOnly = true; ParameterList.Add(PC1.NextValue()); } catch (Exception ex) { ParameterList.Add(-1); } finally { //檢查變數項目是否足夠 ParameterListIndexCheck(WebSite[2], SYSModel.LogLevel.Waring, "" ); //寫入DB ProcLog.WriteLog(ParameterList, null ); PC.Close(); PC1.Close(); } } } } }
/// <summary> /// 寫入Information Log /// </summary> private void InformationLogProcess() { string URLStr = Request.ServerVariables["URL"].ToString(); string[] WebSite = URLStr.Split('/');//位置2為小模組目錄名稱 //Config存放路徑 //string ConfigFilePath = Server.MapPath("/" + WebSite[1] + "/Config/"); //string LogFilePath = Server.MapPath("/" + WebSite[1] + "/LOG"); XmlDocument xdoc = new XmlDocument(); string LogSettingFilePathAndName = string.Format("{0}/{1}", Application["Config_Path"].ToString(), LogSettingFile ); xdoc.Load(LogSettingFilePathAndName); XmlNodeList RootNodeList = xdoc.SelectNodes("ProcessFile/add"); for (int i = 0; i < RootNodeList.Count; i++) { string ProcessFile = RootNodeList[i].Attributes["File"].Value; SYSModel.LogLevel LogLevelProc = (SYSModel.LogLevel)int.Parse(RootNodeList[i].Attributes["LogLevel"].Value); //如果所有程式或特定程式的Log等級設為Information if ( (( ProcessFile== "*") && (LogLevelProc == SYSModel.LogLevel.Information)) || (( ProcessFile== this.PageCode+".aspx") && (LogLevelProc == SYSModel.LogLevel.Information)) ) { SYSModel.LogHelper ProcLog = new SYSModel.LogHelper(ConnectionDB); SYSModel.RequestStruct[] Rqs = new SYSModel.RequestStruct[Request.Form.Count]; StringBuilder sb = new StringBuilder(); sb.Remove(0, sb.Length); for (int j=0;j<Rqs.Length;j++) { //Rqs[j].ControlID = Request.Form.GetKey(j); //Rqs[j].Value = Request.Form.GetValues(j)[0].ToString(); ; sb.AppendFormat("控制項名稱:{0},內容{1};", Request.Form.GetKey(j).ToString(), Request.Form.GetValues(j)[0].ToString() ); } ParameterList.Clear(); //Server名稱 ParameterList.Add(Request.ServerVariables["Server_Name"]); //模組名稱 ParameterList.Add(WebSite[2]); //URL ParameterList.Add(Request.Path); //LOGLEVEL ParameterList.Add(SYSModel.LogLevel.Information); //錯誤訊息 ParameterList.Add("紀錄Information"); //控制項內容 ParameterList.Add(sb.ToString()); //SQL語法 ParameterList.Add(""); try { //使用者 ParameterList.Add(Session["UID"].ToString()); } catch (Exception ex) { //使用者 ParameterList.Add("SessionUID Timeout"); } PerformanceCounter PC = new PerformanceCounter(); PerformanceCounter PC1 = new PerformanceCounter(); try { //目前記憶體總量 PC.CategoryName = PerformanceCounter_TotalMemoryCategoryName; PC.CounterName = PerformanceCounter_TotalMemoryCounterName; PC.InstanceName = PerformanceCounter_TotalMemoryInstanceName; PC.ReadOnly = true; ParameterList.Add(PC.NextValue()); } catch (Exception ex) { ParameterList.Add(-1); } finally { try { //未釋放的記憶體 PC1.CategoryName = PerformanceCounter_HeapMemoryCategoryName; PC1.CounterName = PerformanceCounter_HeapMemoryCounterName; PC1.InstanceName = PerformanceCounter_HeapMemoryInstanceName; PC1.ReadOnly = true; ParameterList.Add(PC1.NextValue()); } catch (Exception ex) { ParameterList.Add(-1); } finally { //檢查變數項目是否足夠 ParameterListIndexCheck(WebSite[2], SYSModel.LogLevel.Information, sb.ToString() ); //寫入DB ProcLog.WriteLog(ParameterList, null ); PC.Close(); PC1.Close(); } } } } }
public void TestMergeTableTiming(int mergeMax, int size) { PerformanceCounter PC = new PerformanceCounter(); PC.CategoryName = "Process"; PC.CounterName = "Working Set - Private"; PC.InstanceName = Process.GetCurrentProcess().ProcessName; Console.WriteLine("TESTING: page max({0}) record count({1})", mergeMax, size); var basename = "RazorDbTests.IndexingTests"; var rand = new Random((int)DateTime.Now.Ticks); var indexHash = new Dictionary<ByteArray, byte[]>(); var itemKeyLen = 35; var kvsName = string.Format("MergeTableTiming_{0}_{1}", mergeMax, DateTime.Now.Ticks); var sw = new Stopwatch(); sw.Start(); using (var testKVS = new KeyValueStore(Path.Combine(basename, kvsName))) { // add a bunch of values that look like indexes for (int r = 0; r < size; r++) { var indexLen = (int)(DateTime.Now.Ticks % 60) + 50; var indexKeyBytes = dataset[r]; var valuekeyBytes = indexKeyBytes.Skip(indexKeyBytes.Length - itemKeyLen).ToArray(); testKVS.Set(indexKeyBytes, valuekeyBytes); // old style index indexHash.Add(new ByteArray(valuekeyBytes), indexKeyBytes); } TableManager.RunTableMergePass(testKVS); } sw.Stop(); var memsize = Convert.ToInt32(PC.NextValue()) / (int)(1024); Console.WriteLine("Total processing time: {0} entries {1} mergeSz {2} MEMORY: {3}", size, mergeMax, sw.Elapsed.ToString(), memsize); Console.WriteLine(); PC.Close(); PC.Dispose(); }
private void Process() { while (!finalizeService) { PerformanceCounter PC = new PerformanceCounter(); PC.CategoryName = "Processor"; PC.CounterName = "% Processor Time"; PC.InstanceName = "_Total"; PC.ReadOnly = true; var value = PC.NextValue(); Thread.Sleep(1000); value = PC.NextValue(); PC.Close(); PC.Dispose(); PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes", true); var ramValue = ramCounter.NextValue(); if (ramValue < MinRAMAvailable) { SendAlertMessage(AlertType.RAM_ALERT, value,Convert.ToInt64(ramValue)); } if (value > MaxCPUUsage) { totalHits = totalHits + 1; if (totalHits == Period) { SendAlertMessage(AlertType.PROCESS_ALERT, value, Convert.ToInt64(ramValue)); totalHits = 0; } } else { totalHits = 0; } } eventLog.WriteEntry(ServiceName + " stoped."); }
/// <summary> /// Releases the performance counter. /// </summary> /// <param name="performanceCounter">The performance counter.</param> private static void ReleasePerformanceCounter(ref PerformanceCounter performanceCounter) { if (performanceCounter != null) { performanceCounter.Close(); performanceCounter = null; } }
private void AdjustConcurrentScanCount_Tick(object sender, EventArgs e) { const int cpuRequiredPerProcess = 20; // actual is closer to 20 const int cpuBuffer = 20; // always save 30% CPU for random spikes const int mBytesRequiredPerProcess = 40; // actual is closer to 60 const int mBytesBuffer = 400; // always save 500mb of RAM for random spikes var cpuCounter = new PerformanceCounter {CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total"}; var ramCounter = new PerformanceCounter {CategoryName = "Memory", CounterName = "Available MBytes"}; cpuCounter.NextValue(); // for some reason this returns 0 on the first call ramCounter.NextValue(); Thread.Sleep(500); int freeCycles = 100 - Convert.ToInt32(cpuCounter.NextValue()) - cpuBuffer; long freeMBytes = (long)ramCounter.NextValue() - mBytesBuffer; int allowedViaCPUCalc = (freeCycles + cpuRequiredPerProcess * HostWorker.ScanProcessList.Count) / cpuRequiredPerProcess; int allowedViaRAMCalc = Convert.ToInt32((freeMBytes + mBytesRequiredPerProcess * HostWorker.ScanProcessList.Count) / mBytesRequiredPerProcess); HostWorker.AllowedConcurrentScanCount = Math.Min(allowedViaCPUCalc, allowedViaRAMCalc); cpuCounter.Close(); ramCounter.Close(); }
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(); }
public override async Task<State> Poll() { ServerManager server = null; ObjectState stateResult = ObjectState.Unknown; State state = default(State); try { server = ServerManager.OpenRemote(serverInstance.Name) ; if (server != null&& this.Exist()) { state = new State(); state.Url = string.Concat(this.Name, "@", serverInstance.Name); stateResult = server.ApplicationPools[Name].State; if (stateResult == ObjectState.Started) { if (server.ApplicationPools[Name].WorkerProcesses.Count > 0) { WorkerProcess wp = server.ApplicationPools[Name].WorkerProcesses .Where(p => p .AppPoolName.ToLowerInvariant() == Name.ToLowerInvariant()) .FirstOrDefault(); PerformanceCounter cpuCounter = new PerformanceCounter("Process" , "% Processor Time" , Process.GetProcessById(wp.ProcessId, serverInstance.Name).ProcessName , serverInstance.Name); cpuPercent = cpuCounter.NextValue(); await Task.Delay(2000); cpuPercent = cpuCounter.NextValue(); await Task.Delay(30000); //the requests interval time is now 30000 int numOfRequests = wp.GetRequests(30000).Count; float cpuPercentAfterThirthySeconds = cpuCounter.NextValue(); if (cpuPercent >= _cpuAlertTreshold && cpuPercentAfterThirthySeconds >= _cpuAlertTreshold) { state.Status = "High CPU Load"; state.Description =string.Format("The CPU for app pool {0} on {1} has reach {2}% and may cause HTTP 503 errors", Name, serverInstance.Name, cpuPercent); state = GetCommonState(server, state, numOfRequests); } else { state.Status = _positiveStatusCode; } if (!string.IsNullOrEmpty(state.Status)) { server.Dispose(); cpuCounter.Close(); cpuCounter.Dispose(); } } else { state.Status = _positiveStatusCode; } return state; } else { state.Description = stateResult == ObjectState.Started ? string.Format("The app pool on server {0} is in the following in {1} state, the number of worker processes is {2}", serverInstance.Name, stateResult.ToString(), server.ApplicationPools[Name].WorkerProcesses.Count) : "Unavailable"; state.Status = stateResult == ObjectState.Started ? _positiveStatusCode: "App Pool Not Started"; state = GetCommonState(server, state, 0); if (stateResult == ObjectState.Stopped) { server.ApplicationPools[Name].Start(); state.Description += server.ApplicationPools[Name].State == ObjectState.Started ? "\rResolution: The appPool was started" : state.Description; } } } } catch(Exception ex) { state.Status = ex.GetType().Name; state.Description = "'polling failed with" + ex.Message; state.Url = string.Concat(this.Name, "@", serverInstance.Name); return state; } return state; }
// 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]]); } }