We have a tool that manages several processes of a computer and from time to time in uncertain conditions we get an InvalidOperationException
when accessing the MSDN: Process.ExitTime property.
The exception message says
process was not started by this object, so requested information cannot be determined
Does that mean that I can only get the exit time of a process that I've started myself? That's not documented anywhere.
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.
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