What is more efficient to use, DispatcherTimer
or Thread.Sleep
in C#?
I could use DispatcherTimer
:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(20);
timer.Tick += timer_Tick;
timer.Start(); // do something every 20 seconds
Or, I could use Thread.Sleep
:
while(true) {
Thread.Sleep(20000);
// do something every 20 seconds
}
In which cases should we use them? Are there any best practices?
Edit: Based on the first answers, I need to add that the application I am developing has no UI (so a blocking thread is no issue), as it is a background tracker, that just writes its data into a logfile.
If you need to operate in the dispatcher thread, then you really don't want to use Thread.Sleep
- you'd end up blocking the dispatcher thread, so your user interface would be frozen.
You could have a background thread sleeping for 20 seconds between actions and using Dispatcher.Invoke
to execute the action on the dispatcher thread, but that seems pretty pointless to me. DispatcherTimer
is simpler to use than that and it avoids having another thread with its own dedicated stack.
Now that you've indicated that you don't actually have a UI, DispatcherTimer
is the wrong choice as there's no dispatcher involved. I would instead use one of the other timer classes, such as System.Threading.Timer
. Using a timer indicates the intent (doing something repeatedly) more clearly than just having a separate background thread, in my view. I wouldn't worry about the efficiency of either solution, however.
See more on this question at Stackoverflow