在C#中,可以使用Process
类的Kill()
方法来终止子进程
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// 启动一个子进程
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
process.StartInfo = startInfo;
process.Start();
// 等待5秒钟
System.Threading.Thread.Sleep(5000);
// 终止子进程
if (!process.HasExited)
{
process.Kill();
Console.WriteLine("子进程已终止。");
}
else
{
Console.WriteLine("子进程已经退出。");
}
}
}
在这个示例中,我们创建了一个新的Process
对象并启动了一个名为"notepad.exe"的子进程。然后,我们让主线程休眠5秒钟。接下来,我们检查子进程是否已经退出。如果没有,我们调用Kill()
方法来终止子进程。最后,我们输出相应的消息。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:怎么在C++中安全的终止子进程