开发者

get all processes in parallel

I'm trying to get the CPU% for all processes in parallel using C#'s TPL. The code that I have is:

        private IDictionary<Process, int> _usage = new Dictionary<Process, int>();

        public ProcessCpuUsageGetter()
        {            
            Process[] processes = Process.GetProcesses();
            int process开发者_如何学GoCount = 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);
        }

But it fails with An item with the same key has already been added. Any ideas on what I'm doing wrong?


The problem is the closure of the local variable i when passed to the expression for starting the task. This causes current value of i used by the DoWork(processes[i]) even when i being modified by the for.

Create a local variable:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜