题
如果在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分钟后关闭
解决方案
使用 Process.WaitForExit
超时两分钟,然后调用 进程.Kill
如果 WaitForExit
返回 false
。
(您也可以考虑致电 CloseMainWindow
而不是 Kill
,取决于你的情况 - 或者至少先尝试一下,让这个过程更有机会有序关闭。)
其他提示
使用System.Threading.Timer并提供一个TimerCallback(包含你的process.Kill),在2分钟后回调。 请参阅此处的示例
//p1.Kill(startingTime.AddMinutes(2));
using (var timer = new Timer(delegate { p1.Kill(); }, null, 2000, Timeout.Infinite))
{
Console.ReadLine(); // do whatever
}
编辑:Jon的解决方案更简单..更少的类型..没有处置要求。
您应该尝试使用Windows服务而不是控制台应用程序。 Windows服务具有迭代生命周期,因此可以使用Windows服务中的计时器控件轻松实现。让计时器以一定间隔打勾并在特定时间间隔内执行所需的操作。
当然,您也可以使用控制台应用程序进行计时器控制。
不隶属于 StackOverflow