Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the-nose-knows/309df85c55c686edfaae1a3130fb4e27 to your computer and use it in GitHub Desktop.
Save the-nose-knows/309df85c55c686edfaae1a3130fb4e27 to your computer and use it in GitHub Desktop.
A countdown timer written in C# 7.1+ using an async main method and an async task delay
using System;
using System.Threading.Tasks;
namespace CountdownTimer
{
class Program
{
public static async Task Main( string[] args )
{
int delay = 500; // Default delay
bool parsedSuccessfully = false;
try
{
if ( args.Length > 0 )
{
parsedSuccessfully = Int32.TryParse( args[0], out delay ); //This overwrites `delay` with 0 if it fails to parse.
}
if ( !parsedSuccessfully || delay < 1 ){ delay = 500; }
else if ( delay > 60000 )
{
Console.WriteLine( "[Long-Wait WARNING]: delay.exe was scheduled to run for {0} seconds.", (float)delay / 1000 );
Console.WriteLine( "Select this console and press 'CTRL' + 'C' on your keyboard to quit earlier." );
Console.WriteLine( "Alternatively, you can \"End task\" this delay.exe using the Task Manager's \"Details\" tab." );
}
else if ( delay > 2000 ){ Console.WriteLine( "delay.exe will be running for {0} seconds.", (float)delay / 1000 ); }
var delayInterval = TimeSpan.FromMilliseconds( delay );
await DoActionAfter( delayInterval, () => Console.WriteLine( "Delay of {0} milliseconds completed.", delay ) );
}
catch( Exception e ){ Console.WriteLine( "Internal error from delay.exe: {0}", e.Message ); }
}
public static Task DoActionAfter( TimeSpan delay, Action action ) => Task.Delay( delay ).ContinueWith( _ => action() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment