In order to access the exit time information, the Process
class needs to have an open Handle for the processa. Whilst e.g. WaitForExit
will temporarily create a handle, unfortunately it closes that handle before returning.
We can force the Process
class to permanently open a handle to the process by accessing its Handle
or SafeHandle
properties1. However, we should notice that there is still some raciness here since between constructing the Process
object and accessing the SafeHandle
property the process could exit.
Start an instance of Notepad, find its process ID and edit it into the first line of Main
here:
using System;
using System.Diagnostics;
namespace PlayAreaCSCon
{
internal class Program
{
public static void Main(string[] args)
{
var p = Process.GetProcessById(18148);
//var sh = p.SafeHandle;
p.WaitForExit();
Console.WriteLine(p.ExitTime);
Console.ReadLine();
}
}
}
Once this program is running, exit Notepad and observe that we get the exception you've mentioned. Clean up and start another copy of Notepad. This time, after editing the process ID in, also uncomment the line that mentions SafeHandle
.
Once this program is running once again, exit Notepad. Observe that this time we get the exit time. So you can hopefully see how this exception can arise and I think we'd both agree that the message is woefully incomplete.
aAnd it cannot magic one into existence for a process that has already exited.
1There are probably lots of extra entry points that indirectly cause these properties to be accessed and so side-effect the Handle into existence - but these are the most obvious routes for forcing the handle open.