waleed.makarem
waleed.makarem

Reputation: 301

.net thread.sleep inaccurate

I am getting crazy !!. I am sending audio over gsm and by voice specifications, I must send voice date packets then wait for 20 milliseconds to get normal voice. I use system.threading.thread.sleep(20). However, I noticed that sound is slow .But when i run another different application , sound gets normal.

After some debugging, i found that system.Threading.Thread.Sleep(20) takes 31 milliseconds , but if I run another different application, the Thread.Sleep (20) will always be accurate.

what are the other alternatives that I can use in order to make the thread sleep for 20 Milli-seconds accurately & at the same time does not impact PC performance.

Thanks,

Upvotes: 1

Views: 581

Answers (2)

jamespconnor
jamespconnor

Reputation: 1412

As mentioned, accurate timings generally need a thread/process that is not going to time sliced out, to do this, you must Spin rather than Sleep.

Option 1

If you want absolute accuracy over anything else, I would use a dedicated high priority thread with a Stopwatch.

bool running = true;
Thread t = new Thread(() =>
{
    Stopwatch sw = Stopwatch.StartNew();
    while (running)
    {
        if (sw.ElapsedMilliseconds >= 20)
        {
            RunCode();
            sw.Restart();
        }
    }
}) { Priority = ThreadPriority.Highest, IsBackground = true };

t.Start();

// ...

running = false;
t.Join();

Option 2

Bit more slimmed down, doesn't run on a different thread but still spins.

while (true) 
{
    SpinWait.SpinUntil(() => false, TimeSpan.FromMilliseconds(20));
    RunCode();
}

Option 3

Some open source high resolution timer code. e.g. https://gist.github.com/HakanL/4669495

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Sleep(20) means sleep for at least 20 ms. Basically, it suspends the thread and doesn't resume scheduling for the specified delay. After that the thread still has to be scheduled to actually resume running. Depending on what other threads are running that could be immediately or some time later. There are no guarantees here.

The documentation calls this out:

The system clock ticks at a specific rate called the clock resolution. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks. For more information on clock resolution and the waiting time, see the Sleep function topic. This method calls the Sleep function from the Windows system APIs.

Upvotes: 2

Related Questions