views:

159

answers:

2

I have a program that executes another program and the main program continues when that program is finished.

Process p = Process.Start("program2.exe");

while (!p.HasExited)
    Thread.Sleep(10000);

if (p.HasExited)
{
    // Execute more code
}

This works great as when I run the program. But does not work when it is used as a scheduled task in windows. this part never executes

if (p.HasExited)
{
    // Execute more code
}

Can't seem to find a way to debug this. I've been stuck on this program for a week now.

+1  A: 

Your code would be simpler if you assume that once p.HasExited is true that it stays that way. You can then remove the if statement. Then there's only three remaining ways I can see that your code can give the result you see:

  1. The second process never exits. Can you see it in Task manager?
  2. Your code throws an exception. Are you logging exceptions somewhere?
  3. The second process exits, but never reports HasExited.

Can you try to investigate and eliminate 1 and 2 first? It is a good idea to look at the simple alternatives first.

Update: From the comments Andrew Keith also suggested that the code might not be being executed at all. Insert log statements liberally so you can see exactly what is going on. Log to a file for example.

Mark Byers
how would I insert the the log feature? and where? im new to c# thanks
Peter
If you want to integrate logging into your project you could look at [log4net](http://logging.apache.org/log4net/index.html). If you want something more lightweight you could use [System.Diagnostics.Trace](http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx).
Mark Byers
A: 

My guess is a security related issue with the user the scheduled task is running as. Ie: the program works fine as you, but as the scheduled task user it is not allowed to execute "program.exe" (or even worse, you program).

You can check the task scheduler log (in the task scheduler control panel -> advanced menu). It should give an exit code for your task as zero (or maybe one). Something is not right if you're getting a very large exit code.

Oh, and Process.WaitForExit() is probably cleaner than your polling loop.