Invalid Operation Exception from C# Process Class

ぃ、小莉子 提交于 2019-12-14 00:16:25

问题


When I use VSTS debugger to see the properties of instance of class Process, many of the properties are marked with InvalidOperationException. Why? Am I doing anything wrong?

I am using VSTS 2008 + C# + .Net 2.0 to develop a console application.

Here is my code:

System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "IExplore.exe";
myProcess.StartInfo.Arguments = @"www.google.com";
myProcess.StartInfo.Verb = "runas";
myProcess.Start();

And a screenshot of the debugger:


回答1:


Had you actually started the process when the debugger picture was taken? That's the screenshot I'd expect to see before the Start() method is called.

Note that the common pattern is to create a ProcessStartInfo, populate it, and then call the static Process.Start(startInfo) method. That makes it conceptually simpler: you don't see the Process object until it's been started.




回答2:


Yes, this is expected behavior and it is clearly documented in MSDN as well.

For example, Process.BasePriority Property can throw an InvalidOperationException exception when the process has exited or the process has not started (see more details in MSDN).




回答3:


Many of the properties are marked with InvalidOperationException because until you start the process . The object 'myProcess' is not associated with any running process and hence it cannot get the information.

Try adding these statements, after the code to start the process

if (myProcess != null)  
{
  myProcess.WaitForExit();
   //or any other statements for that matter
}

Now, when you are inside the if statement, the VSTS debugger will be able to show most of the properties associated with the object myProcess. This happens because, myProcess object is now associated with a running process "IExplore.exe".



来源:https://stackoverflow.com/questions/1151903/invalid-operation-exception-from-c-sharp-process-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!