Skip to content

Instantly share code, notes, and snippets.

@romipetrelis
Created November 7, 2017 15:00
Show Gist options
  • Save romipetrelis/e3cab64cdd53e54ca136cda8e5c4e654 to your computer and use it in GitHub Desktop.
Save romipetrelis/e3cab64cdd53e54ca136cda8e5c4e654 to your computer and use it in GitHub Desktop.
console app with cancel-able infinite loop
// credit: https://stackoverflow.com/questions/35714547/c-sharp-console-application-run-for-loop-while-not-disturbing-rest-of-exec
class Program {
static void Main(string[] args){
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
var backgroundTask = Task.Run(() =>
{
Console.WriteLine("Background task started");
long count = 0;
while (!cancellationToken.IsCancellationRequested)
{
//TODO: do your thing
count++;
}
Console.WriteLine("task cancelled");
return count;
}, cancellationToken);
Console.WriteLine("Back in main");
Console.ReadKey();
tokenSource.Cancel();
Console.WriteLine("Counter: {0}", backgroundTask.Result);
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment