Skip to content

Instantly share code, notes, and snippets.

@noseratio
Created July 9, 2021 11:37
Show Gist options
  • Save noseratio/984a43777138458aeb4806e2b54472af to your computer and use it in GitHub Desktop.
Save noseratio/984a43777138458aeb4806e2b54472af to your computer and use it in GitHub Desktop.
A simple console loop
using System;
using System.Threading;
using System.Threading.Tasks;
namespace App
{
class Program
{
static async Task<int> Main()
{
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += async (_, args) =>
{
args.Cancel = true;
await Task.Yield();
cts.Cancel();
};
try
{
await RunLoopAsync(cts.Token);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return ex.HResult;
}
return 0;
}
static async Task RunLoopAsync(CancellationToken token)
{
while (true)
{
await Task.Delay(1000, token);
Console.WriteLine($"On thread: {Thread.CurrentThread.ManagedThreadId}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment