Reputation: 36512
Given a particular System.Diagnostics.Process that has been assigned values to its properties .FileName
and .Arguments
, what is the best way to determine if it:
.Start()
command orIf .Start()
was never issued, then calling .CloseMainWindow()
causes an InvalidOperationException, which I'd like to avoid.
Upvotes: 5
Views: 6341
Reputation: 10616
If you're closing a process by calling .CloseMainWindow()
, wrapping the call in a try/catch block is the correct thing to do.
Do this:
try
{
process.CloseMainWindow()
}
catch (InvalidOperationException)
{
// purposely do nothing here - the process exited before we told it to.
}
This is because checking the process properties before shutting the process down creates a race condition: both the property check and the call to .CloseMainWindow()
are racing to see which can complete first.
Consider this series of events:
process.HasExited
and receives false
false
, your code calls process.CloseMainWindow()
, and gets an InvalidOperationException: Process has exited, so the requested information is not available.
No amount of speeding up your code, nor using locks, nor any other strategy can guarantee that the process won't exit after your if
statement. There is always the race condition. So instead, use try/catch
.
If you need to keep track of whether the process has ever been launched, you may want to wrap the process in your own class. You can use a lock when launching the process and set a boolean flag to indicate that it has been launched.
class ProcessWrapper
{
public HasStarted;
public ProcessWrapper(Process p, ProcessStartInfo psi)
{
// do argument and filename validation etc. here
lock(HasStarted)
{
p.Start(psi);
HasStarted = true;
}
}
}
Upvotes: 4
Reputation: 300549
Have you tried checking Process.Id
and one of the Exit properties ?
Ref.
In response to poster's comments: perhaps you will have to wrap in a try/catch and an exception being thrown indicates not started? It's not pretty!
Upvotes: 3
Reputation: 14105
You could try and check
process.StartTime & process.HasExited
process.Handle
or perhaps use
process.WaitForExit
Upvotes: -3