简体   繁体   中英

Thread.Sleep not working!

consider the following code that is executed in every instantiation of a certain class:

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

After adding 2 or 3 values to each Dictionary it throws "an element with the same key already exists in the dictionary". This should be impossible since i'm doing Sleep after each loop. I've tried, unsuccessfully, to prevent this problem by adding the updateDateTime variable.

I'm running out of ideas. Can anyone help me or explain me how this can happen?

Thanks

Are either _cpuUsage or _ramUsage static by any chance? Or perhaps you've assigned the same value to both of them? If you could give us a short but complete program which demonstrates the problem, it would make things a lot clearer.

On a side note, you seem to be hoping that your usage of ElementAt(0) will remove the earliest entry from the dictionary, but there's no guarantee of that.

From what you're doing, it looks like you'd be better off with a LinkedList<Tuple<DateTime, long>> or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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