using System; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; class A { static int Main(string[] args) { try { int period = 5; int tolerate = 8; using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = 50040; sock.Connect(IPAddress.Loopback, port); NativeHigh(period, tolerate, sock); } } catch (Exception ex) { Console.Error.WriteLine(ex); } return 0; } static void NativeHigh(int period, int tolerate, Socket sock) { var t = CreateWaitableTimerEx(null, null, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); SetWaitableTimer(t, 0, period, null, IntPtr.Zero, false); Stopwatch timer = Stopwatch.StartNew(); const int ms = 10000; for (int i = 0; ; i++) { WaitForSingleObject(t, INFINITE); var n = timer.ElapsedTicks; timer.Restart(); sock.Send(new byte[i % 1400 + 1]); if (n > period * ms + tolerate * ms / 2) Console.WriteLine("{0} {1}", i, n); if (n > period * ms + tolerate * ms) break; } CancelWaitableTimer(t); CloseHandle(t); } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern IntPtr CreateWaitableTimerEx(SECURITY_ATTRIBUTES sa, string name, uint flags, uint access); [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetWaitableTimer(IntPtr h, in ulong due, int period, TIMERAPCROUTINE cb, IntPtr ctxt, bool resume); [DllImport("kernel32.dll", SetLastError = true)] static extern bool CancelWaitableTimer(IntPtr h); [DllImport("kernel32.dll", SetLastError = true)] static extern uint WaitForSingleObject(IntPtr h, uint ms); [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr h); delegate void TIMERAPCROUTINE(IntPtr ctxt, uint lo, uint hi); const uint CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = 0x00000002; const uint INFINITE = ~0U; const uint TIMER_ALL_ACCESS = 0x001F0003; } [StructLayout(LayoutKind.Sequential)] class SECURITY_ATTRIBUTES {}