HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Kill dead instances of Excel on a server

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
killexcelinstancesdeadserver

Problem

We have several legacy programs (VB6) generating Excel report. They are scheduled tasks running on a server. Yes, violate this.

As a result, we've got lots of "dead" instances of Excel on the server. I intend to write a program to clean these dead Excels. What is the correct way to kill an idle instance? I know it's not a good practice but it seems to be the easiest way for me.

Process[] procs = Process.GetProcessesByName("EXCEL");

List beginProcessInfoList = new List();
foreach (Process p in procs)
{
    if (p.HasExited)
        continue;
    try
    {
        ProcessInfo pi = new ProcessInfo() { PID = p.Id, TotalProcessorTime = p.TotalProcessorTime };
        beginProcessInfoList.Add(pi);
    }
    catch (Exception exp)
    {
        this.Log(exp.Message);
    }
}

Thread.Sleep(TimeSpan.FromSeconds(10));

foreach (Process p in procs)
{
    if (p.HasExited)
        continue;
    try
    {
        p.Refresh();
        if (p.TotalProcessorTime - beginProcessInfoList.Single(pi => pi.PID == p.Id).TotalProcessorTime == TimeSpan.FromSeconds(0))
        {
            p.Kill();
            p.WaitForExit();
            this.Log(string.Format("EXCEL started at {0} killed at {1}.", p.StartTime, DateTime.Now));
        }
    }
    catch (Exception exp)
    {
        this.Log(exp.Message);
    }
}

Solution

Your code appears to be correct - however, this can be dangerous because it will kill ALL instances of Excel that are running so you run the risk of killing one of your currently running legacy programs. There are proper ways to clean up Excel resources - see my question here for a C# version. Do you have any ability to update the legacy programs? If so, I would recommend that over this.

Context

StackExchange Code Review Q#5319, answer score: 4

Revisions (0)

No revisions yet.