I'm looking to add a module to one of my utility classes that functions as a countdown timer for tools that execute tasks after a certain amount of time. The code below is what I have working for PoC, but when I went to make this and check out existing examples, none really seemed this slim/simple without going all-out on lambdas, so I'm worried that I'm doing something wrong, or at the very least very inefficiently.
The time-range expected for the tool will be from 200 milliseconds to a few hours.
using System;
namespace CountdownTimer
{
class Program
{
static int Main(string[] args)
{
int aDelay = 2000;
CountDown(aDelay);
return 0;
}
static void CountDown(int delayInMilliseconds)
{
bool finishedCountdown = false;
DateTime initialTime = DateTime.UtcNow;
while (!finishedCountdown)
{
DateTime timeNow = DateTime.UtcNow;
TimeSpan timeDifference = timeNow - initialTime;
if (timeDifference.TotalMilliseconds >= delayInMilliseconds)
{
finishedCountdown = true;
}
}
}
}
}
I also have this alternative when I was futzing around with async, which I'm kind of new to in C#
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CountdownTimer
{
class Program
{
static int Main(string[] args)
{
var result = CountDownTimer(5000);
Console.ReadKey(true);
return 0;
}
async static Task CountDownTimer(int delay)
{
Task myDelay = AsyncDelay(delay);
await myDelay;
}
async static Task AsyncDelay(int delay)
{
await Task.Delay(TimeSpan.FromMilliseconds(delay));
Console.WriteLine("Done");
}
}
}
I think they're both pretty easy to understand, but my uncertainty with C#'s async for the second solution and the CPU cycles being used for the first worry me...
side note: Any version of .NET is available for use