Process.ExitCode fails

G

Guest

I am trying to get the exit code of an application (IE) after the process
closes. On my system I keep getting an exception error. "No process is
associated with the object." The Process class is suppose to keep some
administrative information available on a closed process (i.e., the ExitCode,
HasExited, etc.) but it seems to not do this. Does anyone know how to get
around this problem?

The code is a simple C# form with a button. The button's click code is below.

private void button1_Click(object sender, EventArgs e)
{
Process spawned = Process.Start("iexplore.exe");
Thread.Sleep(2000);
if (spawned.Responding)
{
Thread.Sleep(10000);
spawned.CloseMainWindow();
spawned.Close();
spawned.Refresh();
int exitCode = spawned.ExitCode;
}
}
 
G

Guest

I found out that the Close() method caused all references to the process to
be gone. I removed it and all worked well.
 
P

Peter Duniho

I am trying to get the exit code of an application (IE) after the process
closes. On my system I keep getting an exception error. "No process is
associated with the object." The Process class is suppose to keep some
administrative information available on a closed process (i.e., the
ExitCode, HasExited, etc.) but it seems to not do this.

Your code explicitly frees all resources associated with the process and
then explicitly tells the Process instance to discard all information it
has cached with the process. I don't find it surprising that you cannot
at that point retrieve the exit code.

IMHO, your code should look more like this:

Process spawned = Process.Start("iexplore.exe");

Thread.Sleep(2000);
if (spawned.Responding)
{
int exitCode;

Thread.Sleep(10000);
spawned.CloseMainWindow();
spawned.WaitForExit();

exitCode = spawned.ExitCode;
}
else
{
spawned.Kill();
}

Note that I also added the else clause to kill the process if you've given
up on it. It's not very nice to start a process and then just leave it
around if you decide it's not doing what you want it to. If your code
sample has left out additional management you're doing to prevent this,
then obviously you can ignore that addition.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top