Can Process.HasExited be true for the current process?

I recently saw some kind of production code:

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

It makes sense? Intuitively, if a process exits, code cannot be run in it.

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

If this could make any difference, the precedent for this was to avoid making statements such as objects that are not deleted in the process.

+8
c #
source share
3 answers

Checking the source code of IsExited , it turns out that nothing spectacular happens. IsExited asks the OS whether the process has completed and what the exit code was. What is it.

The entire topic of output redirection does not apply.

The code you found there will always be false. Delete it and find out who wrote it to ask what he had in mind. Perhaps a misunderstanding.

+3
source share

From Thread.IsBackground :

As soon as all the foreground threads belonging to the process are complete, the common language runtime terminates the process. Any remaining background threads stop and do not end.

For me, this means that no thread will ever execute any code after the process terminates.

Regarding the expression from Process.HasExited :

When standard output is redirected to asynchronous event handlers, it is possible that output processing will not be completed when this property returns true. To ensure that asynchronous event processing is complete, call the WaitForExit () overload, which does not accept the parameter before checking HasExited.

I do not think this is applicable, because async event handlers are threads in the current process, and they will be terminated if the process itself should terminate. They can only be executed if they are tied to another process.

+1
source share

In fact, you seem to be able to build such a scenario:

see note at http://msdn.microsoft.com/en-US/library/system.diagnostics.process.hasexited.aspx :

When standard output is redirected to asynchronous event handlers, it is possible that output processing will not be completed when this property returns true. To ensure that asynchronous event processing is complete, call the WaitForExit () overload, which does not accept the parameter before checking HasExited.

0
source share

All Articles