-1

I know, I know, there are many questions and good answers on how to kill a process after x time in C#.

However after reading and writing the code to achieve this task, I find that is impossible to kill a process after a X time. Due to my novice in C#, I find difficult to understand the cause of error and correct it.

The task I want to achieve is to kill a process after 40 minutes, that process is started by a button click. I'm writing to the console:

private void click_start(Object sender, RoutedEventArgs e) {

  using(Process p = Process.Start(@"calc.exe");
  {
   try{
      p.WaitForExit(5000);
      if(!p.HasExited) {
        p.kill();
        Console.WriteLine("Kill process waitforexit is false");
       } else {
        Console.WriteLine("NO Kill, waitforexit is true");
       }
     }
    catch (Exception ex) {
       Messageox.Show(ex.Messaage);
    }
}

Of all the answers in SO, this is the generalized accepted answer.

When running the code on VS 2015, the debugger gives me this error: "Can't process the request because the Process is finished." Also always get the same console line: No kill which indicates that WaitForExit is still true. This after waiting more than 10 minutes event the time to kill is set to less than one minute.

So I don't understand: I launched the process but when ordered to kill, it's yet finished?

4

2 回答 2

0

一个好的 ole 怎么样timer......虽然共识正在使用WaitForExit......

Process p = Process.Start(@"cal.exe");
using (var t = new Timer(delegate { p.Kill(); }, null, 5000, Timeout.Infinite))
{ 
  //what to do?
}
于 2017-04-28T19:04:42.670 回答
0

像这样试试

if(!p.WaitForExit(5000))
    p.kill();

我不确定您的流程的动态,但是,特别是在调试期间,您可能在一个或另一个调用之间有相对显着的延迟,这可能会导致这种行为。

于 2017-04-28T18:11:35.480 回答