开发者

What are the reasons Process.HasExited can throw InvalidOperationException?

开发者 https://www.devze.com 2022-12-26 09:03 出处:网络
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 t开发者_JAVA技巧hrown. Under what co

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 t开发者_JAVA技巧hrown. Under what conditions does this exception get thrown?


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.


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.


The documentation states that an InvalidOperation exception is thrown in no process is associated with the object.

Have you already started the process using Process.Start() or was the process disposed before you are accessing the HasExited property?

This post also deals whith the same issue.


If the above two answers take in mind that process's instance members aren't thread safe, so that might be the next place to start looking.


Don't call Terminate.Close(), call Terminate.CloseMainWindoe() instead.

You may then issue a timed wait, check for HasExited and call Kill() if required.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号