Alex
Alex

Reputation: 36111

C# System.Diagnostics.Process: how to exit a process if it takes more than, say, 10 seconds?

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?

Upvotes: 1

Views: 2702

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You could use the WaitForExit method:

if (!p.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
{
    // timeout exceeded while waiting for the process to exit
}

Upvotes: 12

twon33
twon33

Reputation: 533

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

Upvotes: 2

GvS
GvS

Reputation: 52518

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).

Upvotes: 1

Related Questions