Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top