我很好奇是否有一种简化的方法可以编写这段代码,或者更有效。
我想等待新的notepad.exe存在,只有当它不在列表中时才将该进程添加到进程列表或进程ID列表中,同时删除该列表中不存在的任何进程了。然后在无限循环中重复。
public static List<int> Clients = new List<int>();
while(true)
{
foreach (int r in Clients)
if (!ProcessExists(r))
{
Clients.Remove(r);
Console.WriteLine(r + " was removed.");
break;
}
bool check = false;
Process[] initial = Process.GetProcessesByName("notepad");
foreach (Process i in initial)
{
foreach(int r in Clients)
{
if (i.Id == r)
{
check = true;
}
}
if (check == false)
{
Clients.Add(i.Id);
Console.WriteLine(i.Id + " was added.");
}
check = false;
}
Thread.Sleep(250);
}
private static bool ProcessExists(int id)
{
return Process.GetProcessesByName("notepad").Any(x => x.Id == id);
}
答案 0 :(得分:1)
使用Linq:
可以更简单地处理删除的第一个循环Clients.RemoveAll(p => !ProcessExists(p));
或者这样,保留日志:
Clients.RemoveAll(p => {
if (!ProcessExists(p)) {
Console.WriteLine(p + " was removed.");
return true;
}
return false;
});
对于第二个循环,您可以使用Contains()
类的List<>
方法:
Process[] initial = Process.GetProcessesByName("notepad");
foreach (Process i in initial)
{
if (!Clients.Contains(i.Id))
{
Clients.Add(i.Id);
Console.WriteLine(i.Id + " was added.");
}
}