[英]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.