I am implementing a communication algorithm to send information periodically and very fast, i.e. 1ms between packs. I've a functional version that uses Tasks to send the packs. Here an example of my code:
private void Work()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (!cancellationTokenSource.Token.IsCancellationRequested)
{
if (!Pack.PeriodicOn)
cancellationTokenSource.Cancel();
// Time used to send the packs before the interval time
double tolerance = Pack.Interval * 0.2F;
// In case of interval bigger than 25ms send pasks only 5ms before
if (tolerance > 5) tolerance = 5;
TimeSpan timeSpan = stopwatch.Elapsed;
// The waiting time is controlled by the condition below, if the condition is false, the while loop continues execution
// Send the information a little bit before to interval time to deal with the transmision delay
if (Pack.LastSent.TotalMilliseconds == 0 ||
timeSpan.TotalMilliseconds - Pack.LastSent.TotalMilliseconds >=
(Pack.Interval - tolerance))
{
SendData(Pack);
Pack.LastSent = timeSpan;
}
}
Pack.LastSent = new TimeSpan(0);
}
My problem relies in the fact that the CPU usage increases to an undesirable levels. I know that I can avoid that by introducing some delay, but, Thread.Sleep(1) is very inaccurate and the real transmission interval between packs rises, if I use await Task.Delay(1) seems to produce the same effect.
Does anybody have an alternative way to introduce, accurately, delay in tasks?
Thanks in advance!