Maxime Joyal
Maxime Joyal

Reputation: 183

best tool for countdown?

I need to start a timer and to check if it's time is elapsed. For example, at the start of my function, I give 30 seconds, then do some stuff, then wait until the 30 seconds are elapsed to go on.

I could use a Timer, which seems like a bazooka (the object offers way too much possibilities for what I need it) for the current situation. I could also take a Stopwatch, and check when it is more than 30 seconds.

However, the perfect tool if it exists would be more a combination of both: having a variable to which I set to 30 seconds, and then a property would be true/false when finished.

I know the tools mentioned above works, but for the reason explained, I wondered if there is better?

Upvotes: 2

Views: 228

Answers (2)

Eric Lippert
Eric Lippert

Reputation: 660297

  • To tell how long something took, use Stopwatch.
  • To have an event fire when some time has elapsed, use Timer.
  • To introduce a delay in an asynchronous workflow, use await Task.Delay(x)

The tools have been provided for you; choose the one that fits your job.

Upvotes: 13

Anton Gogolev
Anton Gogolev

Reputation: 115819

An appropriate Timer (there are two in .NET BCL, pick carefully) is just fine. If you feel adventurous, try ThreadPool.RegisterWaitForSingleObject.

Upvotes: 1

Related Questions