James Dunne James Dunne - 4 months ago 29
C# Question

Need microsecond delay in .NET app for throttling UDP multicast transmission rate

I'm writing a UDP multicast client/server pair in C# and I need a delay on the order of 50-100 ┬Ásec (microseconds) to throttle the server transmission rate. This helps to avoid significant packet loss and also helps to keep from overloading the clients that are disk I/O bound. Please do not suggest Thread.Sleep or Thread.SpinWait. I would not ask if I needed either of those.

My first thought was to use some kind of a high-performance counter and do a simple while() loop checking the elapsed time but I'd like to avoid that as it feels kludgey. Wouldn't that also peg the CPU utilization for the server process?

Bonus points for a cross-platform solution, i.e. not Windows specific. Thanks in advance, guys!


I would use stopwatch but would need a loop

read this to add more extension to the stopwatch, like ElapsedMicroseconds

or something like this might work too

System.Diagnostics.Stopwatch.IsHighResolution MUST be true

    static void Main(string[] args)
        Stopwatch sw;
        sw = Stopwatch.StartNew();
        int i = 0;

        while (sw.ElapsedMilliseconds <= 5000)
            if (sw.Elapsed.Ticks % 100 == 0)
            { i++; /* do something*/ }