Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top