Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a Process in a using statement without WaitForExit()?

In the following example, what happens to the process if it is still running once the code leaves the using statement?

using (var p = new Process())
{
    p.StartInfo.FileName = "c:\\temp\\SomeConsoleApp.exe";
    p.Start();
}
like image 754
user1172282 Avatar asked Dec 04 '14 17:12

user1172282


2 Answers

One should separate the OS process that is running on your system from the Process object that represents a "handle" to it in your program:

  • The process continues running until it completes, or you kill it using OS-specific methods
  • The Process object gets disposed, so your program can no longer interact with the OS process.

Call of Dispose() method on the Process object does not kill the OS process.

like image 146
Sergey Kalinichenko Avatar answered Oct 14 '22 23:10

Sergey Kalinichenko


As you might know using statement will call Dispose method, so the process instance will be Disposed.

To interact with the process, to get the process related information you need Handle to the Process. .Net framework internally holds the Handle to the process and takes all the pain for you. Dispose will close the process Handle and thus you'll not be able to make use of Process object in a good way anymore.

And most important thing: Nothing happens to the process which you started, it runs as if nothing happens. Really nothing happened, you just lost the key to the door, doesn't mean that room is destroyed.

like image 21
Sriram Sakthivel Avatar answered Oct 14 '22 23:10

Sriram Sakthivel