简体   繁体   中英

.NET processes in Task Scheduler

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM