假如在 Windows 服务器上调用某些服务,可能因为多种原因导致程序卡在那里。这在 Office PIA 开发中最常遇到,一般调用 WORD 来处理某些任务,会遇到 WORD 的僵死。我们想停掉处理超时的程序,用 .NET 写一个 console 小程序仅仅数行就能达到这个目的:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; namespace WORD_Monitor { class Program { static void Main(string[] args) { System.Console.WriteLine("Monitor service start"); // check every 2 seconds Timer timer = new Timer(new TimerCallback(TimCallBack), null, 1000, 2000); Console.Read(); timer.Dispose(); } public static void TimCallBack(object o) { Process[] proc = null; proc = Process.GetProcesses(); foreach (Process pr in proc) { // only check WINWORD process if (!(pr.ProcessName.IndexOf("WINWORD") < 0)) { DateTime now = DateTime.Now; TimeSpan dtDiff = now - pr.StartTime; // kill the process over 30 seconds if (dtDiff.TotalSeconds > 30) { pr.Kill(); } } } } } }