Joh*_*nny 1 c# asynchronous task-parallel-library
这是一个两部分问题.
我有一个类异步获取所有进程并轮询它们的CPU使用情况.昨天我有一个错误,它在这里解决了.
问题的第一部分是解决方案为何有所帮助.我不明白这个解释.
问题的第二部分是,"Object reference not set to an instance of object"当我尝试在流程结束时打印结果时,我偶尔会遇到异常.这是因为item.Key确实是空的.我不明白为什么那是因为我检查断点(process == null)并且它从未被击中.我究竟做错了什么?
代码如下.
class ProcessCpuUsageGetter
{
private IDictionary<Process, int> _usage;
public IDictionary<Process, int> Usage { get { return _usage; } }
public ProcessCpuUsageGetter()
{
while (true)
{
Process[] processes = Process.GetProcesses();
int processCount = processes.Count();
Task[] tasks = new Task[processCount];
_usage = new Dictionary<Process, int>();
for (int i = 0; i < processCount; i++)
{
var localI = i;
var localProcess = processes[localI];
tasks[localI] = Task.Factory.StartNew(() => DoWork(localProcess));
}
Task.WaitAll(tasks);
foreach (var item in Usage)
{
Console.WriteLine("{0} - {1}%", item.Key.ProcessName, item.Value);
}
}
}
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;
if (process == null)
{
var x = 5;
}
if (_usage == null)
{
var t = 6;
}
_usage.Add(process, cpuPercent);
}
}
Run Code Online (Sandbox Code Playgroud)
这条线
_usage.Add(process, cpuPercent);
Run Code Online (Sandbox Code Playgroud)
正在从线程访问not-threadsafe集合.
使用ConcurrentDictionary<K,V>而不是普通的字典.
'null reference'错误只是一个随机症状,你也可能得到其他错误.
| 归档时间: |
|
| 查看次数: |
578 次 |
| 最近记录: |