C# Source Code: Making sure an application process exits (doesn't linger)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Making sure an application process exits (doesn't linger)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Monday, August 07, 2006
Hits:
2543
Category:
General/Framework
Article:
The code below is for a console application that can be shelled (ie must be built into another exe) while your application is shuting down. It will then kill your application if doesn't exit cleanly within a specified period of time. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace ProcessExitMonitor { ///
/// Simple utility class for kill processes that failed to terminate. ///
class ProcessExitMonitor { [DllImport("USER32.DLL")] private static extern bool IsWindowVisible(IntPtr hWnd); ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { if ( args.Length != 2 ) { Console.WriteLine("Requires 2 commands, the image name and time to wait." ); Console.WriteLine("eg, ProcessExitMonitor.exe Excel, 10000" ); Console.WriteLine("Checks Excel is shut in 10 secs time." ); Console.ReadLine(); } string processName = args[0].Replace("\"", ""); string waitForExitString = args[1].Replace("\"", ""); int waitForExitMs = int.Parse( waitForExitString ); int killCount = 0; Process[] matchingProcs = Process.GetProcessesByName(processName); Console.WriteLine("Found " + matchingProcs.Length + " instances of '" + processName + "'."); foreach( Process proc in matchingProcs ) { if ( !IsWindowVisible( proc.MainWindowHandle ) ) { Console.WriteLine("Waiting for " + waitForExitMs.ToString() + " ms for process " + proc.Id + "..."); if ( !proc.WaitForExit( waitForExitMs ) ) { // Kill the stale process killCount++; Console.WriteLine( processName + " with PID " + proc.Id + " is dead. KILLING PROCESS..."); proc.Kill(); } } else { Console.WriteLine( processName + " with PID " + proc.Id + " still has window open - NOT KILLING PROCESS..."); } } Console.WriteLine("Killed: " + killCount + "."); Console.WriteLine(""); } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet