Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the reasons Process.HasExited can throw InvalidOperationException?

I'm seeing a System.Diagnostics.Process.HasExited method throw an InvalidOperationException, but the message text property is not terribly useful as to why it was thrown. Under what conditions does this exception get thrown?

like image 555
Robert Davis Avatar asked Apr 08 '10 20:04

Robert Davis


2 Answers

I'm seeing the same message. It can happen if you do this:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "trash filename here.exe";
try
{
    proc.Start();
}
catch { }//proc should fail.
try
{
    if (proc.HasExited)
    {
        //....
    }
}
catch (System.InvalidOperationException e)
{
    //cry and weep about it here.
}

If proc.Start() failed above, you should get to cry and weep section, too. So, if you catch after proc.Start() be sure to catch at proc.HasExited (and MANY other of the System.Diagnostics.Process Methods.

like image 56
lmat - Reinstate Monica Avatar answered Nov 03 '22 01:11

lmat - Reinstate Monica


As Obalix correctly states, an InvalidOperationException is thrown when no process is attached to the Process object. This happens when a process has exited and Close or Dispose has been called on the Process object. Close releases all resources related to the process from memory. Before calling Close, this data was kept in memory to provide you (the programmer) with the information you want to know about the exited process, such as it's ExitTime and ExitCode.

like image 36
Daniel A.A. Pelsmaeker Avatar answered Nov 03 '22 01:11

Daniel A.A. Pelsmaeker