What .NET object (or technique) is the most precise at launching a thread every XXX milliseconds? What are the tradeoffs?
For example:
int maxDurationMs = 1000;
while (true)
{
DateTime dt = DateTime.UtcNow;
DoQuickStuff()
TimeSpan duration1 = DateTime.UtcNow - dt;
int sleepTime = maxDurationMs - duration1.Milliseconds;
if (sleepTime > 0)
System.Threading.Thread.Sleep(sleepTime);
}
or
// CPU Intensive, but fairly accurate
int maxDurationMs = 1000;
while (true)
{
DateTime dt = DateTime.UtcNow;
DoQuickStuff()
while (true)
{
if (dt.AddMilliseconds(maxDurationMs) >= DateTime.UtcNow)
break;
}
}
Alternate methods of doing the same thing, but with varying degrees of accuracy and tradeoffs (CPU, etc)
- System.Timer
- DispatchTimer
- System.Threading.Timer
- Thread.Join
- .NET 4.0 Task
- Thread.Sleep()
- Monitor.Wait(obj, timespan)
- Multimedia Timers (thanks Brian Gideon)
- Win32 High Resolution timers
- Something else?