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.
You can use Process. GetProcessesByName Method (String) to find whether a particular process is running or not.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With