3
\$\begingroup\$

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<ProcessInfo> beginProcessInfoList = new List<ProcessInfo>();
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);
    }
}
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Yes, we will update the legacy programs but they are many. Before that, we need a workaround to solve the dead instance issue. Thank you =) \$\endgroup\$ – walterhuang Nov 23 '11 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.