[英]how to get ID process when it is started a new instance?
我正在尝试启动 Firefox 并在几秒钟后将其关闭。 我的代码是这样的:
using (Process myProcess = new Process())
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();
Task.Delay(5000);
Process.Start("taskkill.exe", $"/PID {myProcess.Id}");
}
然后问题是当我在taskkill进程中设置断点时,任务管理器中不存在myProcess.Id。 Firefox 的所有实例都有另一个 ID。
如果我尝试打开记事本,它可以工作,记事本的 ID 是 myProcess 的 ID。
所以我在想,也许用 Firefox 打开一个进程,然后关闭它,然后打开另一个 Firefox 实例。 这是真的?
怎么知道 firefox 的 ID? 或者我怎么能杀死 Firefox 的所有进程? 因为其实我的Firefox进程不止一个,我有很多。
谢谢。
使用Task.Delay(...)
时,您应该await
它,否则您将开始一个新任务并立即忘记它:
您的代码已修改:
//TODO: check if your method is declared as async
private async Task MyMethod() {
...
using (Process myProcess = new Process()) {
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();
// await for 5 seconds delay
await Task.Delay(5000);
// this will be continued after 5 seconds delay
// Do not forget to dispose yet another process - taskkill.exe
// Why not myProcess.Kill(); ?
using (Process.Start("taskkill.exe", $"/PID {myProcess.Id}")) {}
}
代码:(我的版本)
//TODO: check if your method is declared as async
private async Task MyMethod() {
...
// Let's extract model (how to start process) from execution
ProcessStartInfo psi = new ProcessStartInfo() {
UseShellExecute = false,
FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe",
CreateNoWindow = false,
};
// Process.Start can return null, which we forgive with !
using (Process myProcess = Process.Start(psi)!) {
// We, typically, cancel Tasks instead of delaying and analyzing
using (CancellationTokenSource cts = new CancellationTokenSource(5000)) {
try {
// start process with cancellation after 5 seconds
await myProcess!.WaitForExitAsync(cts.Token);
}
catch (TaskCanceledException) {
// if process has been cancelled (not completed) we want to kill it
myProcess!.Kill();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.