繁体   English   中英

Thread.Sleep不工作!

[英]Thread.Sleep not working!

考虑在某个类的每个实例化中执行的以下代码:

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);
    }
}

在为每个Dictionary添加2或3个值之后,它会抛出“字典中已存在具有相同键的元素”。 这应该是不可能的,因为我在每次循环后都在做睡眠。 我尝试通过添加updateDateTime变量来防止此问题,但未成功。

我的想法已经不多了。 谁能帮助我或解释一下这是怎么发生的?

谢谢

_cpuUsage_ramUsage是否有任何机会静态? 或者你可能已经为它们分配了相同的值? 如果你能给我们一个简短而完整的程序来证明这个问题,它会让事情变得更加清晰。

在旁注中,您似乎希望您对ElementAt(0)使用将从字典中删除最早的条目,但不能保证这一点。

从你正在做的事情来看看起来你会更好地使用LinkedList<Tuple<DateTime, long>>或类似的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM