Created
January 25, 2021 16:38
-
-
Save mikehadlow/f742770eb02a4db908dcb4f89d49aa15 to your computer and use it in GitHub Desktop.
A simple framework for a console application periodic loop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using static System.Console; | |
namespace SimpleConsoleLoop | |
{ | |
class Program | |
{ | |
static Task Main() | |
{ | |
var cts = new CancellationTokenSource(); | |
CancelKeyPress += (_, args) => | |
{ | |
cts.Cancel(); | |
cts.Dispose(); | |
args.Cancel = true; | |
}; | |
WriteLine("Starting loop. Ctrl-C to stop."); | |
return RunLoop(cts.Token); | |
} | |
static async Task RunLoop(CancellationToken cancellation) | |
{ | |
try | |
{ | |
while (!cancellation.IsCancellationRequested) | |
{ | |
await Task.Delay(1000, cancellation); | |
WriteLine($"Loop! On thread: {Thread.CurrentThread.ManagedThreadId}"); | |
} | |
} | |
catch (TaskCanceledException) { } | |
catch (Exception exception) | |
{ | |
WriteLine(exception.ToString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment