I have an application that needs to send an audio packet over UDP. To avoid jitter I want to schedule a thread or task to perform this task every 20 milliseconds. The pseudo code looks like this:
while(true)
{
byte[] packet = GetNextPacket();
socket.Send(packet);
var waitUntill = DateTime.Now.AddMilliseconds(20);
while(DateTime.Now < waitUntill) { }
}
This works fine, but it uses 100% of a CPU core. Which is of course undesirable. I've tried playing with Thread.Sleep
and Thread.Yield
and their task equivalents but in all cases I either end up with 100% load or an extremely jittery experience (which is to be expected).
Is there no way in C# to schedule a task at such a fine grained level? I don't need a 100% guarantee (Windows is not a real-time OS) but something that will work most of the time. Note that I'm not worried about the GC :).
I'm fine with calling any COM code to achieve this, though my ideal solution would be multi-platform. I'm currently using dotnet core 3.0.
If it is not possible in C#, how is it achieved in languages like C++ which do perform these kinds of tasks.
Look into using a multimedia timer:
They're specifically designed for these kind of high-resolution applications.