Thread.Sleep does not work!

consider the following code that runs in each instance of a particular 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 displays "an element with the same key that already exists in the dictionary." This should be impossible, as I do Sleep after each cycle. I tried, unsuccessfully, to prevent this problem by adding the variable updateDateTime.

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

thank

+3
source share
1 answer

- _cpuUsage _ramUsage ? , , ? , , , .

, , , ElementAt(0) , .

, , , LinkedList<Tuple<DateTime, long>> .

+3

Source: https://habr.com/ru/post/1793116/


All Articles