我正在尝试比较两个进程列表并仅获得差异(新启动的进程)。 因此,当我单击winform中的按钮时,程序应加载oldProcesses,然后加载newProcesses,在差异和显示差异列表中进行比较。第一次的差异列表应为空,因为oldProcesses和newProcesses是相同的。 但它没有发生,问题在于这个代码:var Difference = newProcesses.Except(oldProcesses).ToList(); 如何区分newProcesses和oldProcesses? 谢谢
Process[] oldProcesses = { };
int clicked = 0;
private void button1_Click_1(object sender, EventArgs e)
{
if (clicked == 0)
{
oldProcesses = Process.GetProcesses();
clicked = 1;
}
Console.WriteLine("Old: " + oldProcesses.Count());
Process[] newProcesses = Process.GetProcesses();
Console.WriteLine("New: " + newProcesses.Count());
var Difference = newProcesses.Except(oldProcesses).ToList();
Console.WriteLine("Diff: " + Difference.Count());
string allproc = "";
foreach(Process theprocess in oldProcesses)
{
allproc += theprocess.ProcessName.ToString() +"\n";
}
MessageBox.Show(allproc);
allproc = "";
foreach (Process theprocess in newProcesses)
{
allproc += theprocess.ProcessName.ToString() + "\n";
}
MessageBox.Show(allproc);
allproc = "";
foreach (Process theprocess in Difference)
{
allproc += theprocess.ProcessName.ToString() + "\n";
}
MessageBox.Show(allproc);
/*Process[] processlist = Process.GetProcesses();
string ProcList = "";
string temp;
foreach (Process theprocess in processlist)
{
temp = theprocess.ProcessName.ToString() + "\n";
ProcList += temp;
}*/
}
答案 0 :(得分:1)
public class ProcessDiff : IEqualityComparer<Process>
{
public IEnumerable<Process> GetDiff(IEnumerable<Process> oldProcesses, IEnumerable<Process> newProcesses )
{
return newProcesses.Except(oldProcesses, this);
}
public bool Equals(Process x, Process y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.Id == y.Id && x.ProcessName == y.ProcessName && x.SessionId == y.SessionId;
}
public int GetHashCode(Process obj)
{
if (obj == null) return 0;
return obj.Id;
}
}
和用法:
var oldProc = Process.GetProcesses();
var newProc = Process.GetProcesses();
var diff = new ProcessDiff().GetDiff(oldProc, newProc);
如果你不想,你实际上不需要为此创建一个单独的类。您也可以创建表单工具IEqualityComparer<Process>
并向其添加所需的Equals()
/ GetHashCode()
方法。 Except
方法有一个包含比较方法的类实例的参数(如果在包含this
方法的同一个类中调用它,则为IEqualityComparer
)。
更新:
我添加了一些额外的约束,因为Process.Id
可以回收。您可能需要根据您的需求来检查其他因素。请记住,Idle
进程会在某些属性上抛出异常。