tags:

views:

72

answers:

3

I tried the following code:

p = StartProcess("some_process.exe");
DateTime startTime = DateTime.Now;
p.Start();
while (!p.HasExited)
{
    executeTime = (DateTime.Now - startTime).Milliseconds;

    if (executeTime > 10000) // 10 seconds
    {
       Console.Write("Test \"" + inputTest + "\" failed: takes more than 10 seconds");
       break;
    }
}

but it doesn't work.

Is it possible to do that?

+10  A: 

You could use the WaitForExit method:

if (!p.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
{
    // timeout exceeded while waiting for the process to exit
}
Darin Dimitrov
I love WaitForExit method! I was using it before but I didn't know it had such a wonderful overload. I thing though. It requires an int value as a parameter so we have to cast TotalMilliseconds value to int.
Alex
I should look at overloads more, this is awesome :)
Blam
@Alex, yeap good remark about the Int32 parameter. A cast is needed. I've updated my post to reflect this.
Darin Dimitrov
We can't edit comments anymore?.. *1 thing though.
Alex
+1  A: 

Call the Kill method on the process variable (p in you example), this will stop the process.

Note: The loop in your example is very CPU intensive. You should use the WaitForExit call to wait 10 seconds (as Darin Dimitrov suggests).

GvS
+2  A: 

The WaitForExit answer is better, because it blocks, but the reason your code doesn't work is because you want TimeSpan.TotalMilliseconds rather than TimeSpan.Milliseconds. Milliseconds gives you something in the range [-999,999]: http://msdn.microsoft.com/en-us/library/system.timespan.milliseconds.aspx

twon33