Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 在一定时间后终止进程+;C#_.net_Process_C# 2.0 - Fatal编程技术网

.net 在一定时间后终止进程+;C#

.net 在一定时间后终止进程+;C#,.net,process,c#-2.0,.net,Process,C# 2.0,我如何在2或3分钟后终止进程查看以下代码: 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 st

我如何在2或3分钟后终止进程查看以下代码:

 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);
        }



    }
}
因此,我希望IE窗口在2分钟后关闭,并超时两分钟,然后调用if
WaitForExit
返回的
false


(您也可以考虑调用而不是<代码>杀戮< /代码>,这取决于您的情况,或者至少先尝试一下,让进程更有机会进行有序的关机)。

< P>您应该尝试使用Windows服务而不是控制台应用程序。Windows服务具有迭代生命周期,因此可以使用Windows服务中的计时器控件轻松实现这一点。让计时器以一定的间隔滴答作响,并在一定的时间间隔内执行所需的操作


当然,您也可以在控制台应用程序中使用计时器控件。

使用System.Threading.timer并提供一个TimerCallback(其中包含您的process.Kill),以便在2分钟后回调。 看


编辑:乔恩的解决方案更简单。。类型更少。。无需处理。

感谢john使用closemain windows方法提供的帮助,该方法非常有效1.WaitForExit(60000);//日期时间结束时间2;p1.关闭主窗口()//endTime2=p1.ExitTime;p1.关闭();
//p1.Kill(startingTime.AddMinutes(2));
using (var timer = new Timer(delegate { p1.Kill(); }, null, 2000, Timeout.Infinite))
{ 
  Console.ReadLine();  // do whatever
}