自动检查并清理iis等待线程
using System;
using System.Diagnostics;
using Microsoft.Web.Administration;
namespace IISClean
{
class Program
{
static void Main(string[] args)
{
int Max = 10;
string poolName = "wneduSSL";
try { Max = int.Parse(args[1]); }catch(IndexOutOfRangeException args1) { }
try { poolName = args[0]; } catch (IndexOutOfRangeException args1) { }
try {
if (!EventLog.SourceExists("IISClean"))
{
EventLog.CreateEventSource("IISClean", "Application");
}
ServerManager manager = new ServerManager();
foreach (WorkerProcess proc in manager.WorkerProcesses)
{
if (proc.AppPoolName == poolName)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
if (p.Id == proc.ProcessId)
{
int i = 0;
string log =poolName+ "存在等待线程:\n";
foreach (System.Diagnostics.ProcessThread T in p.Threads)
if (T.ThreadState == System.Diagnostics.ThreadState.Wait && T.UserProcessorTime.TotalSeconds > 5 && T.WaitReason.ToString() == "UserRequest")
{
i++;
Console.WriteLine(T.Id.ToString() + "\t" + T.StartTime.ToString() + "\t" + T.ThreadState + T.Site);
log += T.Id.ToString() + "\t" + T.StartTime.ToString() + "\t" + T.ThreadState + T.Site +"\n";
}
log += "等待线程" + i.ToString() + "个";
if (i > Max)
{
try { p.Kill();
Console.WriteLine("\ni="+i.ToString()+"已重新启动了w3wp!");
log+=",已超过设置的最大值"+Max.ToString()+",已重新启动了w3wp!";
} catch { }
}
EventLog.WriteEntry("IISClean", log);
}
}
}
} catch (System.UnauthorizedAccessException e) {
EventLog.WriteEntry("IISClean", e.Message + "请使用管理员身份运行!");
}
// catch { EventLog.WriteEntry("IISClean", "有若干不明错误发生。"); }
}
}
}
在计划任务中添加定时任务,检查设定的appPoolName,如果等待线程超过设定值则kill相应w3wp进程。iis会重新启动新进程,达到清理等待线程的目的。
任务行运行:
参数1:appPoolName
参数2:设置限定值,高于此值清理
如 iisclean wxedussl 15,检查iis应用池名为“wxedussl",等待线程超过15重启 iis进程。