考虑以下代码,它在某个类的每次实例化时被执行:
private void StartUpdateThread()
{
runUpdateThread = true;
Thread thread = new Thread(new ThreadStart(UpdateUsages));
thread.Priority = ThreadPriority.BelowNormal;
thread.Start();
}
public void UpdateUsages()
{
DateTime updateDateTime = DateTime.Now;
while (runUpdateThread)
{
if (updateDateTime <= DateTime.Now)
{
_cpuUsage.Add(DateTime.Now, GetCPUUsage());
if (_cpuUsage.Count == 61)
_cpuUsage.Remove(_cpuUsage.ElementAt(0).Key);
_ramUsage.Add(DateTime.Now, GetRamUsage());
if (_ramUsage.Count == 61)
_ramUsage.Remove(_ramUsage.ElementAt(0).Key);
updateDateTime = DateTime.Now.AddSeconds(15);
}
Thread.Sleep(15000);
}
}
在每个字典中添加2或3个值后,它会抛出"字典中已经存在相同键的元素"。这应该是不可能的,因为我在每个循环之后都进行了Sleep。
我尝试通过添加updateDateTime变量来解决这个问题,但没有成功。
我已经想尽了办法。有人可以帮助我或解释一下这是如何发生的吗?
谢谢。