并行获取所有进程

我正在尝试使用C#的TPL并行获取所有进程的CPU%。 我有的代码是:

private IDictionary<Process, int> _usage = new Dictionary<Process, int>(); public ProcessCpuUsageGetter() { Process[] processes = Process.GetProcesses(); int processCount = processes.Count(); Task[] tasks = new Task[processCount]; int counter = 0; for (int i = 0; i < processCount; i++) { tasks[i] = Task.Factory.StartNew(() => DoWork(processes[i])); } Task.WaitAll(tasks); } private void DoWork(object o) { Process process = (Process)o; PerformanceCounter pc = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true); pc.NextValue(); Thread.Sleep(1000); int cpuPercent = (int)pc.NextValue() / Environment.ProcessorCount; _usage.Add(process, cpuPercent); } 

但是失败, An item with the same key has already been added. 任何想法,我做错了什么?

Solutions Collecting From Web of "并行获取所有进程"

问题是传递给表达式来启动任务的本地变量i关闭 。 这会导致DoWork(processes[i])使用的当前值,即使当ifor修改时也是如此。

创建一个局部变量:

 for (int i = 0; i < processCount; i++) { int localI = i; tasks[i] = Task.Factory.StartNew(() => DoWork(processes[localI])); }