2

I have a function which starts a process, waits for exit and than returns the exitcode:

function int login(string pathtofile)
{
    //...
    Process process = new Process();
    process.StartInfo.FileName = pathtofile;
    process.Start();
    process.WaitForExit();
    return process.ExitCode;
}

This is working well. But because its waiting for Exit, it blocks the Window Form (I have a Marquee Progress Bar which is conitnues moving and now obivously stops). I have no idea how to return the exit code async and I couldn't find any possible solution that I understood.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
j0h4nn3s
  • 2,016
  • 2
  • 20
  • 35
  • What about something like this? http://stackoverflow.com/questions/470256/process-waitforexit-asynchronously – jensendp Apr 17 '14 at 13:33

2 Answers2

4

You can use this code:

void Login(string pathtofile)
{
    Process process = new Process();
    process.StartInfo.FileName = pathtofile;
    process.EnableRaisingEvents = true;
    process.Exited += new EventHandler(process_Exited);
    process.Start(); 
}

void process_Exited(object sender, EventArgs e)
{
    Process p = (Process)sender;
    int exitCode = p.ExitCode;
}

But note that the Login function will directly exit after starting the process so you cannot return an integer value. You get the exit code in the function process_exited

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
  • Thanks. This works for me. I just wondered if there is an option to do this within the function... Working anyway now :) – j0h4nn3s Apr 17 '14 at 13:48
0

You can register to the Process.Exit event and handle the exit code there.

myProcess.EnableRaisingEvents = true;
myProcess.Exited += OnMyProcessExited;

And then return the exit status from the OnMyProcessExited method

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321