Check if process has started

C

Corbett

How can I query a new process to determine if it has started yet? For
example:

using System.Diagnostics;
Process cmd = new Process();
cmd.StartInfo = new ProcessStartInfo();
..
..
..
if (!cmd.HasStarted) Response.Write("The process hasn't started yet");
else Response.Write ("The process is running");

I know the .HasStarted property doesn't exist, but what method can be
used to determine if the process object is running?

The HasExited property returns an Invalid Operation Exception if a
..Start hasn't been issued. I could catch the exception and handle it
that way but I don't like catching exceptions as a way of handling
coding issues.
 
M

mail

Hi Corbett,

I understand you don't like provoking exceptions to write your code but
sometimes, as far as I know, they're all you've got.

Take a look at the following code for some ideas, I understand there's
an exception - but there is no attempt to handle it.

int nId = 0;
Process process = new Process ();
process.StartInfo = new ProcessStartInfo("notepad.exe");
process.Start();

try
{
if (process.Id != 0 && !process.HasExited )
{
// its started
Debug.Assert(true);
}
nId = process.Id;
}
catch{}

if (nId > 0)
{
Process[] processes =
Process.GetProcessesByName("notepad");
foreach (Process proc in processes)
{
if (proc.Id == nId )
{
Debug.Assert(true);
}
}
}
 
C

Corbett

Thanks for confirming that catching the exception is really the only
way to accomplish what I'm trying to do. For the record, here is the
method that I ended up creating:

public static bool IsRunning(System.Diagnostics.Process proc)
{
try
{
return (!proc.HasExited && proc.Id != 0);
}
catch
{
return false;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top