Reputation: 22133
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.
Upvotes: 9
Views: 1285
Reputation: 171178
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.
Upvotes: 3
Reputation: 7838
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.
Upvotes: 1
Reputation: 2158
Actually you seem to be able to construct such a scenario:
see the note in http://msdn.microsoft.com/en-US/library/system.diagnostics.process.hasexited.aspx:
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.
Upvotes: 0