Created
July 9, 2021 11:37
-
-
Save noseratio/984a43777138458aeb4806e2b54472af to your computer and use it in GitHub Desktop.
A simple console loop
This file contains 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; | |
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