Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 234
pedrodbsa Avatar asked Jul 31 '26 06:07

pedrodbsa


1 Answers

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.

like image 165
Jon Skeet Avatar answered Aug 02 '26 18:08

Jon Skeet