1

I have two programs that conflict with each other. One of them is a C# console app that is launched by Task Scheduler (Program1) in the middle of the night, the other (Program2) is a C# WPF program that is typically run by users during the day. I attempted to use the following to shut down Program2 from Program1:

public static void CloseProgram2()
{
    var process = System.Diagnostics.Process.GetProcessesByName("Program2").FirstOrDefault();
    if (process != null)
    {
        if (process.CloseMainWindow())
        {
            SpinWait.SpinUntil(() => null == System.Diagnostics.Process.GetProcessesByName("Program2").FirstOrDefault(),
                TimeSpan.FromSeconds(30));
        }
    }
}

For some reason, Program2 does not shut down when Program1 is run from the TaskScheduler. However, if I run Program1 manually, it always shuts down Program2. I have task scheduler set to provide credentials so that Program1 will run whether or not anybody is logged into the computer. I notice that the output window for Program1 is not displayed while it is running from Task Scheduler, but it does successfully run. I am wondering if perhaps Task Scheduler is running Program1 in such a way that it does not see processes that were not started up by Task Scheduler, and that's why Program2 doesn't get shut down.

Any ideas or solutions that can help me close Program2 from Program1 when Program1 is run using TaskScheduler would be greatly appreciated.

Curtis
  • 5,794
  • 8
  • 50
  • 77
  • It's not possible to answer your question without a good [mcve] that reliably reproduces the problem. This would include _exact_ details about how your Task Scheduler task is set up (preferably _code_ that installs the task). But it seems almost certain that the issue is related to the user account under which the console program is run, and what processes that program is able to see and/or terminate. – Peter Duniho Sep 05 '17 at 19:54
  • You can debug this more effectively if you add logging to both the console and WPF programs, so that each can report things relevant to their operation (what processes are returned, whether a `WM_CLOSE` message is received, etc.) – Peter Duniho Sep 05 '17 at 19:54

1 Answers1

0

Found another solution to use. Instead of using proccess.CloseMainWindow() I created a batch file with the following:

taskkill /F /IM Program2.exe

And then just ran that batch file from Task Scheduler.

What's weird, is that I needed to put a blank line before the taskkill command in my bat file. Without it, I get a bunch of gibberish and it says it doesn't know how to run that command. Almost as if garbage was inserted before the taskkill command. Very strange...

Curtis
  • 5,794
  • 8
  • 50
  • 77