how to get ID process when it is started a new instance?
I am trying to start Firefox and after few seconds, close it. My code is this:
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}");
}
Then problem is that when i set a break point in the taskkill process, myProcess.Id doesn't exist in the task manager. All the instances of Firefox has another ID.
If I try to open Notepad, it works, the ID of Notepad is the ID of myProcess.
So I am thinking that perhaps with Firefox it is opened a process, it is closed and then another instance of Firefox it is opened. Is this true?
How could know the ID fo firefox? Or how could I kill all the process of Firefox? Because in fact I don't have only one Firefox process, I have many.
Thanks.
When using Task.Delay(...)
you should await
for it otherwise you start a new task and forget it without any delay:
Your code amended:
//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}")) {}
}
Code: (my version)
//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();
}
}
}