views:

1120

answers:

3

Hi all:

how do i kill a process after say 2 or three minutes look at the following code:

 class Program
{
    static void Main(string[] args)
    {

        try
        {
            //declare new process and name it p1
            Process p1 = Process.Start("iexplore", "http://www.google.com");
            //get starting time of process
            DateTime startingTime = p1.StartTime;
            Console.WriteLine(startingTime);
            //add a minute to startingTime
            DateTime endTime = startingTime.AddMinutes(1); 
            //I don't know how to kill process after certain time
            //code below don't work, How Do I kill this process after a minute or 2
            p1.Kill(startingTime.AddMinutes(2));                
            Console.ReadLine();


        }
        catch (Exception ex)
        {

            Console.WriteLine("Problem with Process:{0}", ex.Message);
        }



    }
}

so I want that IE window closed after 2 minutes

+6  A: 

Use Process.WaitForExit with a timeout of two minutes, and then call Process.Kill if WaitForExit returned false.

(You might also to consider calling CloseMainWindow instead of Kill, depending on your situation - or at least try it first, to give the process more of a chance to do an orderly shutdown.)

Jon Skeet
Thanks for the help john used closemain windows method wich works perfect
fzshah76
A: 

You should try with Windows Service instead of a console application. Windows services have iterative lifecycle so this can be easily achieved using a timer control in windows service. Let the timer tick at an interval and perform desired action upon certain time intervals.

Of course you can use timer control with a console application too.

this. __curious_geek
A: 

Use a System.Threading.Timer and supply a TimerCallback (which contains your process.Kill) to be called back after 2 minutes. See the example here

//p1.Kill(startingTime.AddMinutes(2));
using (var timer = new Timer(delegate { p1.Kill(); }, null, 2000, Timeout.Infinite))
{ 
  Console.ReadLine();  // do whatever
}

Edit: Jon's solution is simpler.. less types.. no Disposal reqd.

Gishu