13

I'm considering use Task.Delay() for a non-stop timer, because it's more simple and readable.

As I'm new to .NET, I see no significant difference between the two codes. Can you show me the difference (if there is any) between them?

// Create variable at some place
DispatcherTimer timer = new DispatcherTimer();

timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += timer_Elapsed;
timer.Start();

// Function other place
void timer_Elapsed(object sender, EventArgs e)
{
    //Do stuff
    }

vs

// Every thing inside a function
async void TaskTimer()
{
    while (true)
    {
        await Task.Delay(5000);
        // Do stuff
    }
}
Qantas 94 Heavy
  • 15,410
  • 31
  • 63
  • 82
Thanh Nguyen
  • 7,634
  • 12
  • 54
  • 102

1 Answers1

8

There are two major differences:

  1. The Task.Delay approach will delay the specified amount of time between cycles, while the DispatcherTimer approach will start a new cycle on the specified cycle time.
  2. Task.Delay is more portable, since it does not depend on a type tied to a specific UI.
Stephen Cleary
  • 406,130
  • 70
  • 637
  • 767
  • I don't care very much about time. I only care it can repeate and perfomance. As far as I know, both create background threads add rise an event callback at the time approach. Do they are same perfomance? – Thanh Nguyen Jan 12 '14 at 11:28
  • Performance is comparable. Neither of them create background threads. – Stephen Cleary Jan 12 '14 at 12:30
  • @StephenCleary: is it correct to use ConfigureAwait(false) unless we want to do stuff on the UI thread? – Dunken Nov 12 '14 at 16:04
  • 3
    @Dunken: Yes, you should use `ConfigureAwait(false)` for every `await` in a method that doesn't require a specific context (such as a UI context). – Stephen Cleary Nov 12 '14 at 16:15