Skip to content

Instantly share code, notes, and snippets.

@mikehadlow
Created January 25, 2021 16:38
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 mikehadlow/f742770eb02a4db908dcb4f89d49aa15 to your computer and use it in GitHub Desktop.
Save mikehadlow/f742770eb02a4db908dcb4f89d49aa15 to your computer and use it in GitHub Desktop.
A simple framework for a console application periodic loop.
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