Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Process.HasExited be true for the current process?

Tags:

c#

.net

I have recently seen some production code to the effect of:

if (Process.GetCurrentProcess().HasExited)
{
    // do something
}

Does this make any sense? Intuitively, if the process has exited then no code can be running inside it.

If not, what would be a good way to tell if the current process is terminating?

If it can be of any relevance, the use case for this was to avoid popping assertions such as objects not disposed when the process is being killed.

like image 466
Asik Avatar asked Aug 27 '13 15:08

Asik


People also ask

How can you tell if a process is completed in C#?

You can use Process. GetProcessesByName Method (String) to find whether a particular process is running or not.

Has exited process?

A value of true for HasExited indicates that the associated process has terminated, either normally or abnormally. You can request or force the associated process to exit by calling CloseMainWindow or Kill.


2 Answers

Checking the source code of IsExited it turns out that nothing spectacular is happening. IsExited asks the OS whether the process has terminated and what the exit code was. That's it.

The whole topic of output redirection does not apply.

The code that you found there will always evaluate to false. Remove it and find out who wrote it to ask what he meant. Probably a misunderstanding.

like image 98
usr Avatar answered Oct 18 '22 08:10

usr


From Thread.IsBackground:

Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

For me, this means that no thread will ever execute any code once the process has been terminated.

As for the statement from Process.HasExited:

When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this property returns true. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter before checking HasExited.

I don't think this applies, because the async event handlers are threads in the current process and they will be terminated if the process itself has to terminate. They may only execute if they are attached to some other process.

like image 44
Alex Avatar answered Oct 18 '22 09:10

Alex