IIS经常出现假死的情况,具体什么时候会出现假死,我就不说了,今天我要写的是如何监控IIS的状态。
程序的功能是:如果IIS是为运行的状态,就重启IIS,如果IIS的连接数达到了设置的连接数,也重启IIS。我写了一个window服务,时刻监控着IIS的运行状态。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Management; using System.Diagnostics; using System.ServiceProcess; using System.Configuration; namespace IISWatcher { public partial class IISWatcher : ServiceBase { public IISWatcher() { InitializeComponent(); } System.Timers.Timer tmr; protected override void OnStart(string[] args) { tmr = new System.Timers.Timer(); tmr.Interval = 6000; tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed); tmr.Enabled = true; } void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { string currentAnonymousUsers = ""; string timeOut = ""; try { currentAnonymousUsers = ConfigurationManager.AppSettings["CurrentAnonymousUsers"]; timeOut = ConfigurationManager.AppSettings["TimeOut"]; ServiceController winSc = new ServiceController("WAS"); if (winSc.Status != System.ServiceProcess.ServiceControllerStatus.Running && winSc.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { StartService("WAS"); } ServiceController sc = new ServiceController("W3SVC"); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Running && sc.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { StartService("W3SVC"); } else { SelectQuery query = new SelectQuery("Select " + currentAnonymousUsers + " from Win32_PerfRawData_W3SVC_WebService where name=\"_total\""); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); int currentAnonUsers = 0; foreach (ManagementBaseObject disk in searcher.Get()) { int.TryParse(disk[currentAnonymousUsers].ToString(), out currentAnonUsers); } if (currentAnonUsers > Convert.ToInt32(timeOut)) { StartService("W3SVC"); } } } catch (Exception ex) { EventLog.WriteEntry("IISWatcherRecord", "ErrorMessage:" + ex.Message, EventLogEntryType.Error); } } static private void StartService(string serviceName) { ServiceController sc = new ServiceController(serviceName); sc.Start(); for (int i = 0; i < 5; i++) { sc.Refresh(); System.Threading.Thread.Sleep(1000); if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 4) { throw new Exception(serviceName + "启动失败!启动时间超过5秒!"); } } } protected override void OnStop() { tmr.Stop(); } } }