Murhaf Sousli
Murhaf Sousli

Reputation: 13296

why Process.WaitForExit doesn't wait?

why Process.WaitForExit doesn't wait?

static void Main(string[] args)
    {
        while (true)
        {
            try
            {
                if (Process.GetProcessesByName("ServerAPPFileManager").Length > 0)
                {
                    Process clsProcess = Process.GetProcessesByName("ServerAPPFileManager")[0];
                    Console.WriteLine(clsProcess.ProcessName);
                    clsProcess.WaitForExit();
                }
                if (System.IO.File.Exists(System.IO.Path.Combine(Environment.CurrentDirectory, "ServerAPPFileManager.exe")))
                {
                    Console.WriteLine("File Found");
                    Process p = new Process();
                    p.StartInfo.Verb = "runas";
                    p.StartInfo.FileName = System.IO.Path.Combine(Environment.CurrentDirectory, "ServerAPPFileManager.exe");
                    p.Start();
                }
            }
            catch(Exception e)
            {
                Console.Write(e.Message);
                System.Threading.Thread.Sleep(1000);
            }
        }
    }

it keeps looping and starting the application again and again!

Edit:

It worked now, It was not working because it was like this clsProcess.WaitForExit(1000);

Upvotes: 2

Views: 7839

Answers (5)

devkiat
devkiat

Reputation: 139

remove it in while statement and add it in a timer.. validate if process.hasexited=true then call again your process otherwise, validate if process.responding=true then wait else force the process kill

Upvotes: 0

Polyfun
Polyfun

Reputation: 9639

The problem may be that you are not calling WaitForExit on the Process object that you've created, but instead on a Process object returned from Process.GetProcessesByName(). Instead, try:

Process p = new Process(); 
// etc
p.Start();
p.WaitForExit();

Upvotes: 0

Alex
Alex

Reputation: 13229

Well, that is the way you coded it. It is waiting for exit, then in the very next if statement it starts it again. And as Jared pointed out it keeps looping with no way to break out. so it starts it, waits for it to exit, and then startsit again

Upvotes: 0

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

Check that if (Process.GetProcessesByName("ServerAPPFileManager").Length > 0) does not return false.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754565

This code is wrapped in a while(true) loop and there are no break, throw or return statements within the body of the loop. It will indeed result in an infinite loop.

If you want to exit the loop once the WaitForExit has finished then you need to introduce a break statement to do so.

clsProcess.WaitForExit();
break;

Upvotes: 5

Related Questions