简体   繁体   中英

WaitForExit() throws exception c#

Below is my code to start the process, have put link for demo only.I want this process to run in background without opening browser. Also 2nd line throws exception

Object reference not set to an instance of an object.

var process=Process.Start("http://www.google.com");
process.WaitForExit();

Because when you start a process indirectly you won't get Process object (then in your case process is always null and second line throws an exception).

Let me explain what I mean with indirectly : if you don't specify an executable but you give a document (or a resource) then it'll be executed through a shell verb. In this case an existing process may be (re)used. In this cases Process.Start() will return null .

Try this:

  • Create an empty Word document 'c:\\test.docx'.
  • Close all Word instances.
  • Execute Process.Start(@"c:\\test.docx"); // Returns a Process instance Process.Start(@"c:\\test.docx"); // Returns a Process instance
  • Execute Process.Start(@"c:\\test.docx"); // Returns null Process.Start(@"c:\\test.docx"); // Returns null

Can you simply solve this? AFAIK you can't because Process uses ShellExecuteEx with a SHELLEXECUTEINFO structure to start the process. Reading SHELLEXECUTEINFO documentation for hProcess field you'll see that:

A handle to the newly started application. This member is set on return and is always NULL unless fMask is set to SEE_MASK_NOCLOSEPROCESS. Even if fMask is set to SEE_MASK_NOCLOSEPROCESS, hProcess will be NULL if no process was launched. For example, if a document to be launched is a URL and an instance of Internet Explorer is already running, it will display the document. No new process is launched, and hProcess will be NULL. Note ShellExecuteEx does not always return an hProcess, even if a process is launched as the result of the call. For example, an hProcess does not return when you use SEE_MASK_INVOKEIDLIST to invoke IContextMenu.

Note if you're running a new process just to open an URL and get a server side generated file then you should follow Damien's suggestion and use a WebClient.DownloadFile() .

Process.Start() can return a null reference:

Return Value Type: System.Diagnostics.Process

A new Process component that is associated with the process resource, or null, if no process resource is started (for example, if an existing process is reused).

(Emphasis mine)

When that happens, you'll get a NullReferenceException when trying to call WaitForExit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM